Laravel - 从 Id 数组中获取 belongsToMany 关系
Laravel - Get belongsToMany relationships from an array of Id's
在 Laravel 7 - 我定义了以下关系:
Group.php
public function services()
{
return $this->belongsToMany('App\Service', 'service_group', 'group_id', 'service_id');
}
Service.php
public function groups()
{
return $this->belongsToMany('App\Group', 'service_group', 'service_id', 'group_id');
}
支点 table 为 service_group
在我的控制器中,用户选择了不同的 group
ID。
然后我需要 return 所有 services
这些组。
如果我只选择了一个组(例如 id 为 3),我可以这样做:
$services = Group::find(3)->services;
foreach($services as $service) {
// ...
}
我将如何从一组组中获取所有服务 [3, 7, 15]
有没有比这样做更干净的方法...
// $groups = [3, 7, 15];
foreach($groups as $group_id) {
$services = Group::find($group_id)->services;
foreach($services as $service) {
// ...
}
}
whereIn
方法验证给定列的值是否包含在给定数组中:
$services = Group::whereIn('id', $groups)->with('services')->get();
您可以使用 findMany
。您还应使用预先加载来避免进行过多的 SQL 查询。 https://laravel.com/docs/8.x/eloquent-relationships#eager-loading
$allServices = Group::with('services')->findMany([3, 7, 15])->map(fn ($group) => $group->services)->flatten();
return $allServices;
再好不过了。
$services = Service::whereHas('groups', function($query) use ($groups) {
$query->whereIn('group_id', $groups);
})
在 Laravel 7 - 我定义了以下关系:
Group.php
public function services()
{
return $this->belongsToMany('App\Service', 'service_group', 'group_id', 'service_id');
}
Service.php
public function groups()
{
return $this->belongsToMany('App\Group', 'service_group', 'service_id', 'group_id');
}
支点 table 为 service_group
在我的控制器中,用户选择了不同的 group
ID。
然后我需要 return 所有 services
这些组。
如果我只选择了一个组(例如 id 为 3),我可以这样做:
$services = Group::find(3)->services;
foreach($services as $service) {
// ...
}
我将如何从一组组中获取所有服务 [3, 7, 15]
有没有比这样做更干净的方法...
// $groups = [3, 7, 15];
foreach($groups as $group_id) {
$services = Group::find($group_id)->services;
foreach($services as $service) {
// ...
}
}
whereIn
方法验证给定列的值是否包含在给定数组中:
$services = Group::whereIn('id', $groups)->with('services')->get();
您可以使用 findMany
。您还应使用预先加载来避免进行过多的 SQL 查询。 https://laravel.com/docs/8.x/eloquent-relationships#eager-loading
$allServices = Group::with('services')->findMany([3, 7, 15])->map(fn ($group) => $group->services)->flatten();
return $allServices;
再好不过了。
$services = Service::whereHas('groups', function($query) use ($groups) {
$query->whereIn('group_id', $groups);
})