Laravel查询多对多

时间:2017-12-26 14:27:04

标签: php laravel laravel-5 eloquent

我需要帮助。我有2个表productscategoriesenter image description here

enter image description here

获取请求发送类别ID。我的问题是:如何使用产品模型构建查询??? (查询如下所示:输出类别ID等于$ request->类别的产品)。表连接已配置,我只需要查询,(我阅读文档,但不要理解它)

2 个答案:

答案 0 :(得分:5)

您可以使用:

$products = Product::whereHas('categories', function($q) use ($categoryId) {
   $q->where('id', $categoryId);
})->get();

了解querying relationships

当然,您需要使用Product关系配置categories模型。

答案 1 :(得分:2)

您已经说过它是多对多关系,所有关系都已配置,您希望使用Product模型来构建查询。在这种情况下,您应该使用whereHas()方法:

Product::whereHas('categories', function($q) use($request) {
    $q->where('id', $request->category);
}))->get();
相关问题