![](/img/trans.png)
[英]Laravel: eloquent orderBy hasOne relation column using with and whereHas
[英]Laravel: eloquent orderBy hasOne relation column using with
我有一个具有hasOne
关系participant
的模型Orders
。
public function participant()
{
return $this->hasOne('App\OrderParticipant', 'order_id');
}
我需要检索Orders
集合排序participant.last_name
我的方法
$orders = \App\Orders::with(['participant',])
->where('user_id', $user->id)
->orderBy('participant.last_name')
->get();
失败:
未定义的表:7错误:缺少表\\“参与者\\” \\ nLINE的FROM子句条目:... 1
收集后我已经尝试对它进行排序
return $orders->sortBy('participant.last_name');
但这根本没有排序
顺便说一句我正在使用postgres
谢谢。
您不能直接通过hasOne订购,必须使用join
$orders = \App\Orders::with([
'participant',
])
->where('orders.user_id', $user->id)
->join('participants', 'orders.user_id', '=', 'participants.id')
->orderBy('participants.last_name')
->select('orders.*','participants.id','participants.last_name')
->get();
您可以通过实现
// eager loading
$orders = \App\Orders::with(['participant'=> function($q){
$q->orderBy('last_name', 'asc/desc');
}
])->get();
看起来有点多余,但是我已经通过使用join
进行了整理。 虽然很丑。 注意select
部分。 没有它,一切都搞砸了
$orders = \App\Orders::select('orders.*')
->with([
'....',
'participant',
'participant.documents',
'participant.participantParent',
'participant.country',
'...'
])
->join('order_participants', function ($join) {
$join->on('order_participants.order_id', '=', 'orders.id');
})
->where('orders.user_id', $user->id)
->where(function($q) {
$q->where('orders.status', '!=', 'completed')
->orWhereNull('orders.status');
})
->orderBy('order_participants.last_name')
->orderBy('order_participants.first_name')
->get();
由于我的查询比上面的问题要复杂一些,因此我以发布整个代码为例。 据我了解, join
必须在where
语句之前
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.