I am struggling to find the Person who has the exact specified cars in the following scenario.
Person Table
id | name
1 | Sachin
2 | Rahul
3 | Saurav
Cars Table
id | name
1 | Audi
2 | Ferrari
3 | BMW
Person Car Table
id | person_id | car_id | color
1 | 1 | 1 | "Red"
2 | 1 | 2 | "White"
3 | 1 | 3 | "Black"
4 | 2 | 1 | "Pink"
5 | 2 | 3 | "Yellow"
6 | 3 | 2 | "Black"
Person class
public function cars()
{
return $this->hasMany(Car::class);
}
Kindly help write a query where I want to find out who is the owner of the exact specified cars.
For eg
car_id = 2 then person_id = 3
car_id = 1,2,3 then person_id = 1
car_id = 1,3 then person_id = 2
car_id = 1,2 the person_id = null
I have comeup with the following query but it is not working:
Person::whereHas('cars', function($q) use($cars) {
foreach($cars as $car) {
$q->where('car_id', $car);
}
})
->first()