Order By before Group By using Eloquent (Laravel)

后端 未结 6 871
无人共我
无人共我 2020-12-03 21:22

I have a \"messages\" table with the following columns

CREATE TABLE `messages` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `fromId` int(11) NOT NULL,
  `toId         


        
6条回答
  •  佛祖请我去吃肉
    2020-12-03 22:11

    I just needed to do something similar with a messages model. What worked for me was applying the unique method on the returned eloquent collection.

    Model::where('toId', $id)
        ->orderBy('createdAt', 'desc')
        ->get()
        ->unique('fromId');
    

    The query will return all messages ordered by createdAt and the unique method will reduce it down to one message for each fromId. This is obviously not as performant as using the database directly, but in my case I have further restrictions on the query.

    Also, there are many more useful methods for working with these collections: https://laravel.com/docs/5.2/collections#available-methods

提交回复
热议问题