Reputation: 1439
In Laravel 5.5 I have a database setup like the ERD image below. I prefer using Eloquent over Query Builder but I'm not sure it can be done by Eloquent.
Relationships
How would I do the following: Start the query with Object A. Through Object A I want to obtain Object(s) B and though Object B I want to obtain the corresponding Object C. The last thing that is required is that the results will be sorted Ascending by the position
column in Object B.
What I've tried myself: With Eloquent get Object A and all Objects of B (this is sorted Ascending on position). Foreach Object of B seek corresponding Object C. But I know this is not the best solution for the problem.
Any advise?
Upvotes: 0
Views: 1347
Reputation: 1439
With help of you guys I came to the best solution I could think off:
ObjectA::with(['ObjectB' => function($query){
$query->orderBy('position', 'asc');
},'ObjectB.ObjectC'])->get();
ObjectA Model
public function ObjectB()
{
return $this->hasMany('App\ObjectB');
}
ObjectB Model
public function ObjectC()
{
return $this->hasOne('App\ObjectC');
}
Upvotes: 0
Reputation: 390
This is what I would probably try to do:
$ObjectA->with('ObjectB.ObjectC')
->join('ObjectB','ObjectA.id','=','ObjectB.object_a_id')
->orderBy('ObjectB.position','asc')
->get();
Upvotes: 0
Reputation: 11
You should be able to do this with eager loading.
Something like:
$result = $ObjectA->with(['ObjectB', 'ObjectB.ObjectC'])->get();
https://laravel.com/docs/5.5/eloquent-relationships#eager-loading
Upvotes: 1
Reputation: 941
I updated the previous comment by Gerson where my edit should be visible until reviewed, but here is how i would do it:
$result = $ObjectA->with(['ObjectB', 'ObjectB.ObjectC'])->get();
Upvotes: 1
Reputation: 67
You can use Eloquent
$data['result'] = ObjectA::join('ObjectB','ObjectA.id','=','ObjectB.object_a_id')
->join('ObjectC','ObjectB.id','=','ObjectC.object_b_id')->get();
Upvotes: 0