Reputation: 11
I have a issue with Eloquent ORM relationship i have company Model and Countries Model, One to Many relationship, I have used following codes.
Company Model
class Company_model extends Model
{
public $table = "company";
public $primaryKey = "id";
public function countries(){
return $this->belongsTo('App\Models\Countries','country','countryId');
}
}
Countries Model
class Countries extends Model
{
public $table = "countries";
public $primaryKey = "countryId";
}
i have used the following code to retrieve the data i want to get company details along with countryName
$companyObj = new Company_model();
$result = $companyObj::with('countries')->get();
i get the results with company and countries details but the countries details come as an array i need it come without array also i need to take the country Name now all the details in the countries table comes to the array.
Now Result
Array ( [0] => Array ( [id] => 1 [companyName] => Test [address] => [country] => 1 [phone] => [email] => [website] => [companyImg] => 1 [create_by] => [create_time] => [countries] => Array ( [countryId] => 1 [countryName] => Test [currency] => [language] => ) ) )
I need the result like
Array ( [0] => Array ( [id] => 1 [companyName] => Test [address] => [phone] => [email] => [website] => [companyImg] => 1 [create_by] => [create_time] => [countryName] => Test ) )
Upvotes: 0
Views: 131
Reputation: 195
You've to add a new method in Company_model
that's have the method that only give the selected fields.
class Company_model extends Model
{
public $table = "company";
public $primaryKey = "id";
public function countries(){
return $this->belongsTo('App\Models\Countries','country','countryId');
}
}
This is the new method.
public function countriesIDs()
{
return $this->belongsTo('App\Models\Countries')->select(['name']);
}
Upvotes: 1
Reputation: 266
It is not possible by laravel "with" query. You have to get it by join query like:
Company_model::join('countries','countries.countryId','=','company.country')->select('company.*','countries.countryName')->get();
Upvotes: 0
Reputation: 1981
You can to do this:
$result = Company_model::leftjoin('countries', 'countries.id', '=', 'company.countryId')->select('company.*', 'countries.countryName')->get();
I hope it would helpful.
Upvotes: 0
Reputation: 457
try this
$result = $companyObj::with('countries')->get()->toArray();
Upvotes: 0