php - 在laravel中首先按关系排序
问题描述
我有两个表:admins 和 log_doctor_infos。admins 表与 hasOne 和 log_doctor_infos throught doctor_id 有关系,就像这样。
在模型管理员中:
public function logDoctorInfo() {
return $this->hasOne(LogDoctorInfo::class, 'doctor_id', 'id');
// Model LogDoctorInfo is log_doctor_infos table
}
在模型 LogDoctorInfo 中:
public function doctor(){
return $this->belongsTo(Admin::class, 'doctor_id', 'id');
// Model Admin is admins table
}
我得到所有数据表单管理员表,我想排序记录与 log_doctor_infos 到顶部的关系。
黄色记录,与 log_doctor_infos 有关系,我想把它排在最前面。
编辑:我在这个查询中使用分页,我真的想获得黄色记录的数量。
谢谢阅读!
在我的控制器中,我有自定义过滤器和分页。帮我。
public function index(Request $request) {
$fullname = $request->query('fullname', NULL);
$phone = $request->query('phone', NULL);
$status = $request->query('status', NULL);
$doctors = (new Doctor)->newQuery();
if ($fullname != NULL) {
$doctors = $doctors->where('fullname', 'LIKE', '%'.$fullname.'%');
}
if ($phone != NULL) {
$doctors = $doctors->where('phone', 'LIKE', '%'.$phone.'%');
}
if ($status != NULL) {
$doctors = $doctors->where('status', $status);
}
$doctors = $doctors
// ->with(array('logDoctorInfo' => function($query) {
// $query->orderBy('updated_at', 'ASC');
// }))
->latest()
->paginate()
->appends([
'fullname' => $fullname,
'phone' => $phone,
'status' => $status
]);
// dd($doctors);
return view('admin.doctors.index', compact('doctors'));
}
解决方案
您可以使用该withCount
方法。
Admin::withCount('logDoctorInfo')
->orderBy('log_doctor_info_count', 'desc')
->paginate(5);
您的控制器将如下所示
public function index(Request $request) {
$fullname = $request->input('fullname', NULL);
$phone = $request->input('phone', NULL);
$status = $request->input('status', NULL);
$doctorQuery = Doctor::query();
if ($fullname) {
$doctorQuery->where('fullname', 'LIKE', '%'.$fullname.'%');
}
if ($phone) {
$doctorQuery->where('phone', 'LIKE', '%'.$phone.'%');
}
if ($status) {
$doctorQuery->where('status', $status);
}
$doctorQuery->withCount('logDoctorInfo')
->orderBy('log_doctor_info_count');
$doctors = $doctorQuery->paginate()
->appends([
'fullname' => $fullname,
'phone' => $phone,
'status' => $status
]);
// dd($doctors);
return view('admin.doctors.index', compact('doctors'));
}
推荐阅读
- typescript - 参数'props'隐式具有'any'类型-Typesript中的vuejs错误
- git - git commit - unstage ;该怎么办?
- node.js - 猫鼬模式如何与 CRUD 操作中的 db 相关联
- shell - 使用linux命令行删除一些文件
- pine-script - Tradingview : Pinescript - 创建 2 系列的 UNION 并隔离系列的最后一个元素
- c - Malloc 错误 - 无法分配给可变大小的对象
- django - django-static-precompiler 抛出错误,没有消息
- audio - alsamixer 中的奇怪状态发生了变化
- java - 为什么我在 java 中的基本堆栈代码没有运行?
- wpf - 如何让类库中的 generic.xaml 仅与 TargetType 一起使用?