How does the laravel many-to-many relationship be filtered by comparing the fields of the intermediate table with the fields of the model?

for example: user favorites

Fields of the three tables:
User: id
Product: id, current_price
product_user: id, user_id, product_id, expected_price

App\User

public function products(){
    return $this->belongsToMany("App\Product")->withPivot("expected_price")
}

how to find items that are currently collected by login users and whose current prices are lower than expected?

at present, what I can think of is to find out all the items in the user"s collection first, and then compare it with the corresponding expected_price with foreach one by one. Is there a more elegant way that laravel comes with?

Mar.02,2021

you can take a look at his final implementation of the sql, found that in fact, just add an additional where condition, and then go to the source code to see if there is a way to compare the intermediate table and the associated table, and turn to a wherePivot , but he compares the intermediate table field with a specific value, we want to compare the fields of the two tables, so what should we do? Use DB::raw directly ~

public function expectProducts()
{
    return $this->belongsToMany('App\Product')->wherePivot('expected_price', '>=', DB::raw('current_price'));
}
Menu