英文:
Laravel sort by relation column using eager loader
问题
我使用laravel encore模板中的Sorter来对<th class="left" style="width:16%;">{{trans('coursestudent.course name')}} {!! (new \Encore\Admin\Grid\Column\Sorter('_sort', 'course', null))->render() !!}</th>
进行排序,然后将列和类型(desc、asc)发送到控制器。
在服务中,我使用了$course_students = CourseStudent::with(['course', 'customer'])
来获取数据,最后使用orderBy进行排序。
if (!empty($request['_sort'])){
if(!empty($request['_sort']['column']) && !empty($request['_sort']['type'])){
$course_students = $course_students->orderBy($request['_sort']['column'], $request['_sort']['type']);
}
}else{
$course_students = $course_students->orderBy('id', 'desc');
};
但是这段代码只能对CourseStudent表的列进行排序,我尝试了很多方法,但仍然不知道如何对其他表进行排序。例如:来自course表的course name和来自customer表的customer name。有人可以帮我解决这个问题吗?
英文:
I used Sorter from laravel encore template to sort <th class="left" style="width:16%;">{{trans('coursestudent.course name')}} {!! (new \Encore\Admin\Grid\Column\Sorter('_sort', 'course', null))->render() !!}</th>
, this will then send back the column, and type (desc, asc) to controller.
And in service i used $course_students = CourseStudent::with(['course', 'customer'])
to get data, finally i use orderBy to sort
if (!empty($request['_sort'])){
if(!empty($request['_sort']['column']) && !empty($request['_sort']['type'])){
$course_students = $course_students->orderBy($request['_sort']['column'], $request['_sort']['type']);
}
}else{
$course_students = $course_students->orderBy('id', 'desc');
};
`
But this code will only sort the table CourseStudent columns, i have try many way but i still dont know how to sort the others. For example: course name from course table and customer name from customer table. Can someone help me with this.
答案1
得分: 1
你需要连接你想要按照顺序排列的表,类似这样的代码:
$course_students->leftJoin('courses', 'courses.id', '=', 'course_students.course_id')
->leftJoin('students', 'students.id', '=', 'cource_students.student_id')
->select('course_students.*');
if (!empty($request['_sort'])){
if(!empty($request['_sort']['column']) && !empty($request['_sort']['type'])){
$course_students = $course_students->orderBy($request['_sort']['column'], $request['_sort']['type']);
}
} else {
$course_students = $course_students->orderBy('id', 'desc');
};
英文:
you have to join the tables you want to order by, something like this:
$course_students->leftJoin('courses', 'courses.id', '=', 'course_students.course_id')
->leftJoin('students', 'students.id', '=', 'cource_students.student_id')
->select('course_students.*');
if (!empty($request['_sort'])){
if(!empty($request['_sort']['column']) && !empty($request['_sort']['type'])){
$course_students = $course_students->orderBy($request['_sort']['column'], $request['_sort']['type']);
}
} else {
$course_students = $course_students->orderBy('id', 'desc');
};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论