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

前端 未结 14 1645
太阳男子
太阳男子 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:11

    I found this method working quite well (for me) to produce a flat array of unique values:

    $uniqueNames = User::select('name')->distinct()->pluck('name')->toArray();
    

    If you ran ->toSql() on this query builder, you will see it generates a query like this:

    select distinct `name` from `users`
    

    The ->pluck() is handled by illuminate\collection lib (not via sql query).

提交回复
热议问题