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?
答案 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');