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

时间:2019-04-25 03:26:07

标签: php laravel laravel-5 laravel-5.7

我有一个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错误:缺少表\“参与者\” \ nLINE 1的FROM子句条目:... 1

我试图在收集后对其进行排序

return $orders->sortBy('participant.last_name');

但这根本不排序

顺便说一句,我正在使用 postgres

谢谢。

3 个答案:

答案 0 :(得分: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 :(得分:1)

您可以通过以下方式实现此目标

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

答案 2 :(得分: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语句

相关问题