首页 > 解决方案 > 在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'));
}

标签: phplaraveleloquenteloquent-relationship

解决方案


您可以使用该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'));
}

推荐阅读