2
votes

So I have a laravel app which contains a host of different models and some are dependent on another. In standard SQL you would use a simple join statement and be done with it. However, Laravels Eloquent Models offers functions to build these relationships easily (i.e hasOne,hasMany etc). So I defined my relationships with the latter method and have actually used them successfully.

In attempt to using the Eloquent model along with its defined relationships here:

 vehicle::with(['colors:id,Color', 'damages:id,Damage','secondaryDamages:id,Damage',
'modeldetails.model','modeldetails.engine_type',
'modeldetails.fuel_type','modeldetails.transmission_type',
'modeldetails.body_type','modeldetails.drive_type, 'modeldetails.model.vendor','auctionday']);

But the problem arises when I attempt to chain this command with whereIn().

     vehicle::with(['colors:id,Color', 'damages:id,Damage','secondaryDamages:id,Damage',
    'modeldetails.model','modeldetails.engine_type',
    'modeldetails.fuel_type','modeldetails.transmission_type',
    'modeldetails.body_type','modeldetails.drive_type, 'modeldetails.model.vendor','auctionday'])
->whereIn([id, $arrayofValuetoMatch]);

See querying "id" for the table works fine, it is when I would query for other columns belong to other tables like 'modeldetails.model.vendor.id' which would cause an **error for Unknown column.**if it was in place of id in the whereIn()

So my question is how would I name the column parameter in a whereIn() method while using laravels eloquent relationships. Or do I need to use the join method to have access to these columns?

Here is the original error

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'vehicle_makes.id' in 'where clause' (SQL: select count(*) as aggregate from vehicles where vehicle_makes.id in (1, 2, 3, 4, 5)).

"vehicle_makes" is the original table name but it doesn't work.

Any help would be greatly appreciated..

1
Are you sure you are using withIn() not whereIn() ? I haven't seen withIn() method in laravelM Khalid Junaid
Sorry was a typoCalixte Simeon

1 Answers

1
votes

What I assume from your question that you want to use filter on related models that are associated with your model you could use whereHas() for this purpose

$vendorIds = [1, 2, 3, 4, 5];
$vehicles= vehicle::with([....])
                  ->whereHas('modeldetails.model.vendor', function ($query) use ($vendorIds) {
                        $query->whereIn('id',$vendorIds);
                  })->get();

Also see section Querying Relationship Existence