Laravel雄辩地按关系列排序

时间:2018-10-24 16:15:52

标签: laravel laravel-5

我有几种关系,特别是我想用来订购列表的一种关系,但是我似乎找不到正确的方式来做。

以下是我的人际关系:

public function date(){
    return $this->hasOne(agent_billings_dates::class,'id','dateID');
}

public function carrier(){
    return $this->hasOne(customer::class,'id','carrierID');
}

以及作为附件添加的两个属性:

public function getItemCountAttribute(){
    return $this->items->count();
}

public function getItemMissingAttribute(){
    return $this->itemIssues->count();
}

public function getBatchSumAttribute(){
    return $this->items->sum('amount');

当我在函数中具有以下内容时,这些显示一切正常:

$batches = agent_billings_batches::with(['date','carrier','carrier.carrierDetails'])
        ->where('status',$request->status)
        ->get();

但是当我这样做时,属性和with会下降(但是日期会适当排序):

$batches = agent_billings_batches::with(['carrier','carrier.carrierDetails'])
        ->join('agent_billings_dates', 'agent_billings_dates.id', '=', 'agent_billings_batches.dateID')
        ->orderBy('agent_billings_dates.date','desc')
        ->where('status',$request->status)
        ->get();

我做错什么了吗?我会很感激任何人能提供的帮助。

谢谢!

1 个答案:

答案 0 :(得分:0)

口才在加载关系时不使用联接。它将它们加载到单独的查询中,因此您不能在查询时使用关系对主要结果进行排序,需要在收集数据后执行以下操作:

$batches = agent_billings_batches::with(['date','carrier','carrier.carrierDetails'])
    ->where('status',$request->status)
    ->get()
    ->sortBy(function ($batch) { 
         return $batch->date->date; 
    });