我有一个products
和products_marks
表。products_marks
表包含user_id
和product_id
,并且表示由用户标记/保存的所有产品。所以,这或多或少有点像观察名单。
我现在的目标是执行一个雄辩的查询,该查询只向我返回某些user_id
的product_marks
表中也存在的产品。对于本例,让我们选择user_id
2。
这是我的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-关系存在