首页 > 解决方案 > 根据子模型/关系对父模型进行排序

问题描述

我有一个模型叫做appointments,每个约会都有一个option_id,通过一对一的关系联系起来,option_id也可以null。期权模型有一个属性datetime_start。我想根据option.datetime_start.

这是我的代码:

$appointments = $user->appointments()
->with(['option'
])
->get();

编辑 :

预约型号:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Appointment extends Model
{
   /**
         * @return \Illuminate\Database\Eloquent\Relations\HasOne
   */
   public function option()
   {
     return $this->hasOne(Option::class, 'id', 'option_id');
   }
}

选项型号:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Option extends Model
{
    protected     $fillable = ["appointment_id",
                               "datetime_start"
    ];

    public function appointment()
    {
        return $this->belongsTo(Appointment::class, 'id','appointment_id');
    }
}

任何帮助将不胜感激。

标签: mysqllaravelormmodeleloquent

解决方案


为了按相关选项模型中的列对约会模型进行排序,您需要在查询中添加一个JOIN以便您可以按相关字段进行排序:

$appointments = $user->appointments()
  ->leftJoin('options', 'options.appointment_id', '=', 'appointments.id')
  ->orderBy('options.datetime_start', 'ASC')
  ->with(['option'])
  ->get();

这将为您提供所有约会,包括那些没有Option的约会 - 那些没有Option并且因此没有datetime_start的约会将在结果列表的开头或结尾全部返回,您需要检查一下。如果您只想与Option约会,请将leftJoin()替换为join()


推荐阅读