Laravel查询多对多(Laravel query many to Many)
我需要帮助。我有2个表products和categories :
获取请求发送类别ID。 我的问题是:如何使用产品模型构建查询??? (查询如下所示:输出类别id等于$ request-> category的产品)。 表连接已配置,我只需要查询,(我阅读文档,但不要理解它)
I need help.I have 2 tables products and categories:
Get request sends category id. My question is: how to build a query using the product model??? (The query looks like this: Output the product where the category id is equal to $ request-> category). Table connections are configured, I only need the query, (I read the documentation, but do not not understand it)
最满意答案
您可以使用:
$products = Product::whereHas('categories', function($q) use ($categoryId) { $q->where('id', $categoryId); })->get();阅读有关查询关系的信息
当然,您需要配置具有categories关系的Product型号。
You can use:
$products = Product::whereHas('categories', function($q) use ($categoryId) { $q->where('id', $categoryId); })->get();Read about querying relationships
Of course you need to have configured Product model with categories relationship.
更多推荐
发布评论