检查是否存在belongsToMany关系-Laravel [英] Check if belongsToMany relation exists - Laravel

查看:79
本文介绍了检查是否存在belongsToMany关系-Laravel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的两个表(客户端和产品)都使用Laravel的blongToMany和数据透视表建立了ManyToMany关系. 现在,我要检查某个客户是否具有某种产品.

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,然后最后在Collection上进行foreach来查找具有您传递的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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆