mysql - 根据子模型/关系对父模型进行排序
问题描述
我有一个模型叫做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');
}
}
任何帮助将不胜感激。
解决方案
为了按相关选项模型中的列对约会模型进行排序,您需要在查询中添加一个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()。
推荐阅读
- python - 如何根据 NaN 之后的下一个有效值等于上一个有效值的条件回填 NaN 值
- google-apps-script - 如果单元格的值低于某个值,则发送电子邮件
- c++ - C++ 模板模板参数
- mysql - 列表包含非聚合列“otpallet_pokemonpalet.p.id”
- java - 为什么我的解决方案不能找到二叉树的最小深度?
- coq - 注入策略能否修改最终目标,或添加无关假设?
- java - [JAVA} A-Star 代码未找到最佳路径
- asp.net - 具有多对多(数组)输入的ajax表单
- qt - 将 QColorDialog 调用到连接到由 qt-designer 定义的小部件的插槽函数时程序崩溃
- android - 如何将旅行词添加到 JSON?