如何使用 Laravel Eloquent 获取每个结果的最后(每个日期)连接行
How to get the last (per date) joined row for each result with Laravel Eloquent
这是我想要实现的目标:
我有一个包含 FormationSession 模型的 Formation 模型。
我需要所有编队,每个编队都是数据库中的最后一个会话。
这是我目前得到的:
$formations = Formation::query()
->with('location')
->with('jobs')
->with('employee')
->with('intervenant.company')
->with(['formation_sessions' => function($query) {
$query->limit(1)->orderBy('start_at', 'desc');
}])
->whereNotNull('update_frequency')
->get();
我被困在这里,我该如何实现?
您可以创建另一个关系,例如
public function formation_sessions_last(){
return $this->belongsToMany('App\FormationSession','formation_id')
->orderBy('start_at')->limit(1);
}
#App\FormationSession => FormationSession Modal
#formation_id => foreign_key
然后可以调用查询
->with('formation_sessions_last')
希望这会有所帮助。
这是我想要实现的目标:
我有一个包含 FormationSession 模型的 Formation 模型。 我需要所有编队,每个编队都是数据库中的最后一个会话。
这是我目前得到的:
$formations = Formation::query()
->with('location')
->with('jobs')
->with('employee')
->with('intervenant.company')
->with(['formation_sessions' => function($query) {
$query->limit(1)->orderBy('start_at', 'desc');
}])
->whereNotNull('update_frequency')
->get();
我被困在这里,我该如何实现?
您可以创建另一个关系,例如
public function formation_sessions_last(){
return $this->belongsToMany('App\FormationSession','formation_id')
->orderBy('start_at')->limit(1);
}
#App\FormationSession => FormationSession Modal
#formation_id => foreign_key
然后可以调用查询
->with('formation_sessions_last')
希望这会有所帮助。