且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检查 belongsToMany 关系是否存在 - Laravel

更新时间:2023-11-26 09:27:46

我觉得官方的做法是这样做的:

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;