Laravel:雄辩的orderBy hasOne关系列与with

Shi*_*ker 0 php laravel laravel-5 laravel-5.7

我有一个OrdershasOne关系的模型participant

public function participant()
{
    return $this->hasOne('App\OrderParticipant', 'order_id');
}
Run Code Online (Sandbox Code Playgroud)

我需要检索Orders排序依据participant.last_name

我的方法

$orders = \App\Orders::with(['participant',])
              ->where('user_id', $user->id)  
              ->orderBy('participant.last_name')
              ->get();
Run Code Online (Sandbox Code Playgroud)

失败:

未定义的表:7错误:缺少表\“参与者\” \ nLINE的FROM子句条目:... 1

收集后我已经尝试对它进行排序

return $orders->sortBy('participant.last_name');
Run Code Online (Sandbox Code Playgroud)

但这根本没有排序

顺便说一句我正在使用postgres

谢谢。

小智 5

您不能直接通过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();


Run Code Online (Sandbox Code Playgroud)