Home > OS >  Laravel Many to many filter by pivot attributes
Laravel Many to many filter by pivot attributes

Time:08-08

I have 2 tables and a pivot table with extra attributes

table cars

id name
1 BMW
2 Mercedes
3 Bugatti

table status

id colors
1 red
2 blue
3 green

car_color pivot

car_id color_id is_stock
1 1 0
1 2 1
1 3 1
3 2 1

this is my relations

    //  Car model
    public function colors()
    {
        return $this->belongsToMany(Color::class)->withPivot('is_stock');;
    }

    //  Color model
    public function cars()
    {
        return $this->belongsToMany(Car::class)->withPivot('is_stock');;
    }

I want get list of Red BMWs where is_stocks = 1 i do it with mysql query like this

    $red_bmw_stocks = DB::table('car_color')->where('is_stocks ', '1');

how can i convert it to eloquent

CodePudding user response:

I think you can use wherePivot

return $this->belongsToMany(Car::class)->wherePivot('is_stock', 1);

according to this doc , from laravel

https://laravel.com/docs/9.x/eloquent-relationships#filtering-queries-via-intermediate-table-columns

CodePudding user response:

$cars = Car::with('colors')->wherePivot('is_stock', 1);
  • Related