[英]Sort Laravel (4.2) Collection by multiple fields
How can I sort a Laravel Collection by multiple fields? 如何按多个字段对Laravel集合进行排序?
Imagine I have an "Exams" model, with a relation to "Patients", with date and score fields. 想象一下,我有一个“考试”模型,与“患者”相关,并带有日期和分数字段。
$exams = Exam::all();
$exams->load('Patient');
Now I want to sort this Collection by the patient name and then by the date of the exam. 现在,我想按患者姓名,然后按检查日期对“收藏”进行排序。
$exams = $exams->sortBy('patient.name');
$exams = $exams->sortBy('date', 'desc');
This doesn't work, it ignores the first sortBy. 这是行不通的,它会忽略第一个sortBy。
How can I achieve this? 我该如何实现?
Many thanks! 非常感谢! :)
:)
Try this: Hope it helps you. 试试这个:希望对您有帮助。
$exams = Exam::with(
['patient' => function($query) {
$query->orderBy('name')
$query->orderBy('date','desc)
}
])
)->get();
You have to join patients. 你必须加入病人。
Something like: 就像是:
$exams = Exam::newQuery()
->join('patients', 'exams.patient_id', '=', 'patients.id')
->orderBy('patients.date', 'DESC')
->get()
;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.