我有一个模型 Orders
与 hasOne
关系 participant
。
public function participant()
{
return $this->hasOne('App\OrderParticipant', 'order_id');
}
我需要检索按 participant.last_name
排序的 Orders
集合
我的做法
$orders = \App\Orders::with(['participant',])
->where('user_id', $user->id)
->orderBy('participant.last_name')
->get();
失败:
Undefined table: 7 ERROR: missing FROM-clause entry for table \"participant\"\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();
关于php - Laravel: Eloquent orderBy hasOne 关系列使用 with,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55841380/