简体   繁体   中英

Laravel query using whereHas

I have 2 models: car painted color, and cars

public function color()
{
    return $this->hasOne(Colors::class)->latest();
}

I need to search the latest painted car color but with whereHas, it's searching all colors

$colors = ['black', 'white'];
$cars->whereHas('color', function($cars) use ($colors) {
          return $cars->whereIn('paint_color', $colors);
});

How can I make whereIn to only query on the latest row?

First of all, since each car could have been painted many colors but you want to retrieve the latest painted color. This means you have a one to many relationship from car to color. Therefore the relationship color should be changed to

public function colors()
{
    return $this->hasMany(Colors::class)
        ->latest();
}

Then to only retrieve the latest color you can call ->limit(1) since the colors are already ordered by the relationship.

$cars = $query->with(['colors', function($query) {
        return $query->limit(1);
    }])
    ->get();

Then you can filter whether the latest color is in your $colors array

$filteredCars = $cars->filter(function($car) {
    return $car->colors->whereIn('paint_color', $colors);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM