Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 Hasmanythrough inverse querying

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?

like image 300
Mirza Vu Avatar asked Jan 05 '23 11:01

Mirza Vu


1 Answers

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);
like image 193
patricus Avatar answered Jan 08 '23 11:01

patricus