【问题标题】:Laravel Eloquent 'withCount' function on multiple joined tables多个连接表上的 Laravel Eloquent 'withCount' 函数
【发布时间】:2020-04-17 10:01:48
【问题描述】:

我有多个 hasMany 关系,我只希望最后一个表的行数。

用户可以在特定日期和时间注册研讨会,因此关系看起来像 'Workshop' -> hasMany 'Date' -> hasMany 'TimeSlot' -> hasMany 'Registration'。

//Workshop Model
public function workshop_dates(){
  return $this->hasMany(WorkshopDate::class);
}

//Date Model
public function workshops(){
  return $this->belongsTo(Workshop::class);
}
public function workshop_times(){
  return $this->hasMany(WorkshopTime::class);
}

//Time Model
public function workshop_dates(){
  return $this->belongsTo(WorkshopDate::class);
}
public function registrations(){
  return $this->hasMany(Registration::class);
}

//Registration Model
public function workshop_times(){
  return $this->belongsTo(WorkshopTime::class, 'workshop_time_id','id');
}

在我的控制器中,我获取所有相关日期和时间段的所有研讨会,但我不希望用户下载所有注册数据。我只希望他们下载每个时间段的注册数量。 我尝试了“withCount”功能:

return Workshop::with('workshop_dates.workshop_times.registrations')->withCount('registrations')

但这给了我错误“调用未定义的方法 App\Workshop::registrations()”

所以我在 Workshop.php 中创建了这个方法,使用 hasManyThrough 的extended version

public function registrations(){
  return $this->hasManyDeep(Registration::class, [WorkshopDate::class,WorkshopTime::class]);
}

但是,现在我得到的是每个研讨会而不是每个时间段的注册总数。

我是 laravel 初学者,花了好几个小时寻找解决方案。感谢所有帮助!

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    您可以将withCount() 与闭包的关系添加如下:

    Workshop::with(['workshop_dates.workshop_times' => function($q) {
                $q->withCount('registrations');                      
       }, 'workshop_dates.workshop_times.registrations'])
       ->get()
    

    否则,像这种方法https://stackoverflow.com/a/41166325/4705339

    【讨论】:

    • 谢谢,就是这样!我删除了第二个数组值,因为我只需要注册计数,而不需要数据。完美运行!
    猜你喜欢
    • 2016-07-22
    • 1970-01-01
    • 2019-09-06
    • 2023-03-28
    • 1970-01-01
    • 2020-06-27
    • 1970-01-01
    • 2018-10-24
    • 1970-01-01
    相关资源
    最近更新 更多