Lars Mertens
Lars Mertens

Reputation: 1439

Laravel Eloquent/DB getting relation by foreign table and order results

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.

enter image description here

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

Answers (5)

Lars Mertens
Lars Mertens

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

Julio Guerra
Julio Guerra

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

Gerson Rodriguez
Gerson Rodriguez

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

Raza Mehdi
Raza Mehdi

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

Maaz
Maaz

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

Related Questions