检查 belongsToMany 关系是否存在 - Laravel

2022-01-08 00:00:00 php laravel laravel-4

我的两个表(客户和产品)有一个使用 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 然后最后执行 foreachCollection 使用您传入的 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;

相关文章