Check if belongsToMany relation exists - Laravel(检查 belongsToMany 关系是否存在 - Laravel)
问题描述
我的两个表(客户和产品)有一个使用 Laravel 的 blongToMany 和一个数据透视表的多对多关系.现在我想检查某个客户是否有某个产品.
Two of my tables (clients and products) have a ManyToMany relation using Laravel's blongToMany and a pivot table. Now I want to check if a certain client has a certain product.
我可以创建一个模型来检查数据透视表,但由于 Laravel 不需要该模型用于 belongsToMany 方法,我想知道是否有另一种方法可以在没有数据透视表模型的情况下检查某种关系是否存在.
I could create a model to check in the pivot table but since Laravel does not require this model for the belongsToMany method I was wondering if there is another way to check if a certain relationship exists without having a model for the pivot table.
推荐答案
我觉得官方的做法是这样做的:
I think the official way to do this is to do:
$client = Client::find(1);
$exists = $client->products->contains($product_id);
这有点浪费,因为它会执行 SELECT
查询,将所有结果放入 Collection
然后最后执行 foreach
Collection
使用您传入的 ID 查找模型.但是,它不需要对数据透视表进行建模.
It's somewhat wasteful in that it'll do the SELECT
query, get all results into a Collection
and then finally do a foreach
over the Collection
to find a model with the ID you pass in. However, it doesn't require modelling the pivot table.
如果您不喜欢这样做的浪费,您可以在 SQL/Query Builder 中自己完成,这也不需要对表进行建模(也不需要获取 Client
模型如果您还没有将其用于其他目的:
If you don't like the wastefulness of that, you could do it yourself in SQL/Query Builder, which also wouldn't require modelling the table (nor would it require getting the Client
model if you don't already have it for other purposes:
$exists = DB::table('client_product')
->whereClientId($client_id)
->whereProductId($product_id)
->count() > 0;
这篇关于检查 belongsToMany 关系是否存在 - Laravel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:检查 belongsToMany 关系是否存在 - Laravel
基础教程推荐
- 超薄框架REST服务两次获得输出 2022-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- 在多维数组中查找最大值 2021-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01