Laravel雄辩:只检索关系中有条目的条目(join)



我有一个productsproducts_marks表。products_marks表包含user_idproduct_id,并且表示由用户标记/保存的所有产品。所以,这或多或少有点像观察名单。

我现在的目标是执行一个雄辩的查询,该查询只向我返回某些user_idproduct_marks表中也存在的产品。对于本例,让我们选择user_id2。

这是我的products.php型号:

public function marks()
{
return $this->belongsToMany('AppModelsUser', 'products_marks', 'product_id', 'user_id')->withTimestamps();
}

这就是我现在想要实现的方式。

我用join执行了一个雄辩的查询。但我怎么能在一段关系中做到这一点呢?

$products = Product::join('products_marks', 'products_marks.product_id', '=', 'products.id')
->where('products_marks.user_id', 2)
->orderBy('created_at', 'desc')
->paginate(10);

致以亲切的问候和感谢!

使用has方法:

$products = Product::has('marks')->where('products_marks.user_id', 2)
->orderByDesc('created_at')
->paginate(10);

检查文档https://laravel.com/docs/8.x/eloquent-relationships#querying-关系存在

最新更新