Laravel eager loading - one to many relation

Viewed 257

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 enrty- 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!

1 Answers

That depends on how you define that relation. if you define a relation in your code like so:

// models/A.php
public function c() {
    return $this->hasMany(C::class);
}

it will use the primary key of A by default, which is id, so that becomes a_id when Laravel prefixes the table name. This then becomes an array of many Cs that belong to A through A.id = C.a_id. You have to pass more parameters to hasMany to define your own keys.

However, the relation you need seems to be a hasOne relation: your A only has one C through A.main_location_id = C.location_id. So you could define a hasOne with manual keys like so:

// models/A.php
public function c() {
    return $this->hasOne(C::class, 'location_id', 'main_location_id');
}

If that is the wrong key, you have to pass extra parameters to the hasOne() relation definition.

If you need both of those relations, simply rename the function (use plural and singular form if you have proper table names), and you can for instance use A::query()->with(['c', 'singleC'])

Related