我有一个模型Orders
与hasOne
关系participant
。
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错误:缺少表格“参与者”的FROM子句条目\ nLINE 1:... 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
声明之前