Laravel查询多对多(Laravel query many to Many)

编程入门 行业动态 更新时间:2024-10-20 13:42:29
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.

更多推荐

本文发布于:2023-08-05 00:20:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1424564.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Laravel   query

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!