4

I have 3 models : Vehicle, Dealer and Province

Eloquent Relationships are as follows:

Vehicle belongsTo Dealer

Dealer hasMany Vehicles

Province hasMany Dealers

Dealer belongs to Province

Province hasManyThrough Vehicles

I wanted to get all vehicles in a specific province , but my code need to start calling from vehicle model, because I am calling many filters to Vehicles.

My code:

 $p = 'Alberta'; $d = Vehicle::whereHas('province', function($q) use ($p) { $q->where('province_name', $p); return $q; })->get(); dd($d); 

Unfortunately getting error

Column not found: 1054 Unknown column 'dealers.province_id' in 'where clause' (SQL: select * from vehicles where exists (select * from provinces where dealers.province_id = provinces.id and province_name = Alberta))

But province_id column do exist in dealers table. How can I make it work?

0

1 Answer 1

10

The HasManyThrough relationship does not have an inverse. Your Province can have many Vehicles through Dealers, but your Vehicle does not belong to a Province. Your Vehicle belongs to a Dealer that belongs to a Province.

Because of this, your whereHas needs to specify the nested relationship:

$p = 'Alberta'; $d = Vehicle::whereHas('dealer.province', function($q) use ($p) { return $q->where('province_name', $p); })->get(); dd($d); 
Sign up to request clarification or add additional context in comments.

2 Comments

One more question please. Can you check this stackoverflow.com/questions/39168103
FYI, this (beautiful) query produces a result set of Vehicles which is "DISTINCT". For example, say that 3 Vehicles match the criteria; the result set will contain only 1 record, not 3. Though the generated SQL query does't actually specify DISTINCT(), the results are distinct based on the criteria. To elaborate, the result set will not always be a single record, but the result set will be distinct on whatever the criteria is. For example, say your criteria matches 10 records which have 3 different values, the result set will contain 3 records. Hope this helps!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.