Laravel查询多对多

问题描述 投票:0回答:2

我需要帮助。我有2张桌子productscategoriesenter image description here

enter image description here

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

php laravel laravel-5 eloquent
2个回答
5
投票

您可以使用:

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

了解querying relationships

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


2
投票

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

Product::whereHas('categories', function($q) use($request) {
    $q->where('id', $request->category);
}))->get();
© www.soinside.com 2019 - 2024. All rights reserved.