Laravel:eloquent orderBy hasOne relation column using with

问题描述 投票:0回答:3

我有一个模型OrdershasOne关系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

谢谢。

php laravel laravel-5 laravel-5.7
3个回答
4
投票

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



1
投票

你可以实现这个目标

  //  eager loading
  $orders = \App\Orders::with(['participant'=> function($q){
             $q->orderBy('last_name', 'asc/desc');
            }
           ])->get();

0
投票

它看起来有点多余,但我已经使用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声明之前

© www.soinside.com 2019 - 2024. All rights reserved.