【问题标题】:Laravel - Get belongsToMany relationships from an array of Id'sLaravel - 从一组 Id 中获取 belongsToMany 关系
【发布时间】:2021-07-28 16:30:07
【问题描述】:

在 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');
}

带有service_group的数据透视表

在我的控制器中,用户选择不同的group id。 然后我需要返回这些组中的所有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) {
      // ...
    }
}

【问题讨论】:

    标签: laravel eloquent relationship


    【解决方案1】:

    会更好。

    $services = Service::whereHas('groups', function($query) use ($groups) {
        $query->whereIn('group_id', $groups);
    })
    

    【讨论】:

      【解决方案2】:

      您可以使用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;
      

      【讨论】:

        【解决方案3】:

        whereIn 方法验证给定列的值是否包含在给定数组中:

        $services = Group::whereIn('id', $groups)->with('services')->get();
        
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-04-26
          • 1970-01-01
          • 2015-11-12
          • 1970-01-01
          • 1970-01-01
          • 2018-05-19
          • 2015-02-22
          • 1970-01-01
          相关资源
          最近更新 更多