Laravel - How to order by a related attribute in hasMany

时间:2018-09-18 20:21:35

标签: php mysql laravel eloquent

I have two entities: Producers and Protocols. Producers has many Protocols.

Problem

Select all producers ordered by their last protocol creation date.

Solution

In order to get this, I tried:

$producers = Producer::join('protocol', 'protocol.producer_id', '=', 'producer.id')
  ->orderBy('protocol.created_at', 'desc');

But just didn't work as expected mainly because I even limited the last protocol. How can I achieve this using Laravel Eloquent?

2 个答案:

答案 0 :(得分:2)

使用groupBy()

$producers = Producer::select('producer.*')
    ->join('protocol', 'protocol.producer_id', '=', 'producer.id')
    ->groupBy('producer.id')
    ->orderByRaw('max(protocol.created_at) desc');

答案 1 :(得分:0)

首先描述生产者模型上最后一个协议的关系

public function last_protocol(){
    return $this->hasOne(Protocol::class)->latest();
}

然后,在您的控制器中

$producers = Producer::with('last_protocol')->get()->sortByDesc('last_protocol.created_at');