【发布时间】: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 初学者,花了好几个小时寻找解决方案。感谢所有帮助!
【问题讨论】: