所以,我有这样的事情:
else
CounselingRequest 结构:
我需要来自 counselingRequests(),当它有相同的lecturer_schedule_id时,它必须只返回最新的CounselingRequest。
示例(现在)来自counselingRequests()的结果:
class Student {
/**
* Get the counseling_requests for the student.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function counselingRequests()
{
return $this->hasMany(CounselingRequest::class);
}
}
预期结果:
id | student_id | lecturer_schedule_id | status | created_at
1 | 1 | 2 | 0 | 2016-09-01
2 | 1 | 2 | 1 | 2016-09-02
3 | 1 | 3 | 1 | 2016-09-02
4 | 1 | 4 | 0 | 2016-09-03
答案 0 :(得分:1)
对于相同的lecturer_schedule_id
,group_by
会选择最后一个,然后按升序排序。
Student::with(['councelingRequests'=>function($query)
{
$query->groupBy('lecturer_schedule_id')
}])->get();
但是你会得到:
id | student_id | lecturer_schedule_id | status | created_at
3 | 1 | 3 | 1 | 2016-09-02
4 | 1 | 4 | 0 | 2016-09-03
2 | 1 | 2 | 1 | 2016-09-02