[英]Sort Eloquent models on relationship (one>many)
I've got a model called "Lesson" which has a ->hasMany()
relationship which represent the dates for this lesson. 我有一个名为“ Lesson”的模型,该模型具有
->hasMany()
关系,该关系表示本课程的日期。
To retrieve every lesson with a date within a certain time-span I use a whereHas
: 要检索在一定时间范围内具有日期的每节课,我使用
whereHas
:
$list = Lesson::whereHas('dates', function ($query) use ($start, $end) {
$query->where('date','>=', $start->format('Y-m-d'))
->where('date','<=', $end->format('Y-m-d'));
})->get()
This works as expected, but I now want to sort the $list
by the 'smallest' date associated with the lesson. 这可以按预期工作,但是我现在想按与课程相关的“最小”日期对
$list
进行排序。
Preferably I wish to use the Eloquent models, as there are some needed methods in the model. 最好是我希望使用Eloquent模型,因为模型中需要一些方法。 But if it's not possible, than a 'plain' sql statement could also be used.
但是,如果不可能,那么也可以使用“普通” sql语句。
You can use the available methods of Laravel collections .This code should do it. 您可以使用Laravel集合的可用方法。此代码应做到这一点。
$sortedLessons = $lessons->sortBy(function ($lesson) {
$dates = $lesson->dates;
$minDate = $dates->sortBy('date');
return $minDate;
});
I assumed that you have a field date in your date model. 我假设您在日期模型中有一个字段日期。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.