How to get distinct values for non-key column fields in Laravel?

前端 未结 14 1681
太阳男子
太阳男子 2020-12-01 09:09

This might be quite easy but have no idea how to.

I have a table that can have repeated values for a particular non-key column field. How do I write a SQL query usin

14条回答
  •  南笙
    南笙 (楼主)
    2020-12-01 09:22

    I had the same issues when trying to populate a list of all the unique threads a user had with other users. This did the trick for me

    Message::where('from_user', $user->id)
            ->select(['from_user', 'to_user'])
            ->selectRaw('MAX(created_at) AS last_date')
            ->groupBy(['from_user', 'to_user'])
            ->orderBy('last_date', 'DESC')
            ->get()
    

提交回复
热议问题