[英]Sort the parent model based on the child model / relationship
I have a model called appointments
, each appointment has an option_id
that is linked through a one to one relationship and the option_id
can also be null
. 我有一个称为
appointments
的模型,每个约会都有一个通过一对一关系链接的option_id
, option_id
也可以为null
。 The option model has a property datetime_start
. 选项模型具有属性
datetime_start
。 I want to sort the appointments based on the option.datetime_start
. 我想根据
option.datetime_start
对约会进行排序。
Here is my code : 这是我的代码:
$appointments = $user->appointments()
->with(['option'
])
->get();
Edit : 编辑:
Appointment model : 预约模式:
<?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');
}
}
Option model : 选项型号:
<?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');
}
}
Any help would be greatly appreciated. 任何帮助将不胜感激。
In order to sort Appointment model by a column from related Option model, you need to add a JOIN to your query so that you can sort by related fields: 为了按相关选项模型中的列对约会模型进行排序,您需要向查询中添加一个JOIN ,以便可以按相关字段进行排序:
$appointments = $user->appointments()
->leftJoin('options', 'options.appointment_id', '=', 'appointments.id')
->orderBy('options.datetime_start', 'ASC')
->with(['option'])
->get();
This will give you all appointments, including those without Option - the ones without an Option and, hence, without datetime_start , will be all returned either at the beginning or the end of the result list, you'll need to check that. 这会给你所有约会,包括那些没有选项 -包括那些没有一个选项 ,因此,没有datetime_start,将全部退回或者在开始或结果列表的末尾,你需要检查。 If you only want appointments with Option , replace leftJoin() with join() .
如果只希望使用Option进行约会,请将leftJoin()替换为join() 。
$appointments = Appointment::with(['option' => function ($query){ $query->orderBy('datetime_start', 'desc'); } ])->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.