在laravel中按关系排序

时间:2019-01-24 09:15:15

标签: php laravel eloquent eloquent--relationship

我有两个表:admins和log_doctor_infos。 admins表在此通过Doctor_id与log_doctor_infos之间具有hasOne关系。

在模型管理员中:

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
}

我从admins表中获取所有数据,并且我想对记录进行排序,与log_doctor_infos的关系到顶部。

黄色记录,与log_doctor_infos有关系,我想将其排在最前面。

编辑:我在此查询中使用分页,我真的想获取黄色记录数量。

感谢阅读!

Example

在我的控制器中,我有自定义过滤器和分页器。救救我。

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'));
}

2 个答案:

答案 0 :(得分:2)

Doctor::with('logDoctorInfo')->get()->sortByDesc('logDoctorInfo.id');

答案 1 :(得分:2)

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