Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

M@rty's avatar
Level 1

Laravel eager loading - one to many relation

Hello laravel dev.

I have three tables let's say A, B, C

A
-----------
-id
-main_location_id // **main location entry = 1**

B
-----------
-id
-a_id
-allocated_qty

C
-----------    
-id
-a_id
-location_id // **main location enrty + other locations entry- 1,2,3**
-total_qty
-aval_qty

Relation:

table A has many of B

table A also has many of C

Query:

A::with(['B'])
->with(['C']) // here I got all location object from C tables, but I only want main_location_id = location_id data object + its qty
->where('a.id', 1)
->first();

I don't understand how will I get location_id, total_qty, aval_qty from table C through table A which has c.location_id = a.main_location_id

Even I don't know if I'm doing right?

is this possible?

please help me with this

Many thanks!

0 likes
20 replies
Tray2's avatar

Have you tried another order?

A::where('id', 1)->with('b')->with('c')->first();
Tray2's avatar

Something like?

SELECT *
FROM a, b ,c
WHERE a.id = c.id
AND a.main_location_id = c.location_id
AND a.id = b.a_id
M@rty's avatar
Level 1

@Tray2 Thanks for the reply

Yes I'm expecting the same result as you have mentioned in the raw query but don't get how to do with eager loading

Tray2's avatar

@M@rty Then use the select that I gave you with the db facade.

DB::select('SELECT *
FROM a, b ,c
WHERE a.id = c.id
AND a.main_location_id = c.location_id
AND a.id = b.a_id');
vincent15000's avatar

If you use with(), the query will return all the fields of the relationship.

What information do you exactly want to retrieve ?

As a similar code, I generally do this.

A::with(['b'])->with(['c'])->find(1);
M@rty's avatar
Level 1

@vincent15000 Actually,

with(['C'])

here I got all location objects from C tables, but I only want main_location_id = location_id data object + its total_qty, aval_qty

vincent15000's avatar

@M@rty How have you declared the relationships in your A model ?

You should have something like this.

public function b()
{
	return $this->hasMany('App\Models\B');
}

public function c()
{
	return $this->hasMany('App\Models\C');
}
vincent15000's avatar

@M@rty Can you do a dd() of the result of your query and post it here ?

vincent15000's avatar

@M@rty I mean this.

$results = A::with(['b'])->with(['c'])->find(1);
dd($results);
jqodirov's avatar
jqodirov
Best Answer
Level 3

@M@rty No you should add use \Awobaz\Compoships\Compoships; to your Model.

In your case relation:

 public function c()
    {
        return $this->hasMany('C', ['a_id', 'location_id'], ['id', 'main_location_id']);
    }
1 like

Please or to participate in this conversation.