Home > Software engineering >  How to get a collection based on column from another collection?
How to get a collection based on column from another collection?

Time:04-08

Let's say I have a collection of Cars and a collection of Accidents. Wherein the Accidents collection, there is a column car_id, which specifies what car has had an accident. What would be a fix to this, to get all collections where...?

Here's what I have accomplished so far.

// Returns an array of numbers
$accidents = Accidents::get()->pluck('car_id')
    ->toArray();

// Returns only one row from collection
$cars = Cars::where('id', $accidents)->get(); 

CodePudding user response:

Try the following code, you have to use whereIn to match with a collection of array.

$cars = Cars::whereIn('id', $accidents)->get(); 

CodePudding user response:

Or, since you are already doing an association. You might as well make it easy on yourself and just do a relationship in the model and do a one to many relationship.

https://laravel.com/docs/8.x/eloquent-relationships#one-to-many

Then all you need to do is call the relationship in eloquent using the with() and run a where the accidents are equal to or greater than 1. This will put everything in a nice collection for you to iterate through on the front.

There are some good examples in the docs.

  • Related