Tuesday, April 19, 2022

[FIXED] How to get a collection based on column from another collection?

Issue

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(); 

Solution

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

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


Answered By - Tayyab mehar
Answer Checked By - Senaida (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.