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

前端 未结 14 1640
太阳男子
太阳男子 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条回答
  •  Happy的楠姐
    2020-12-01 09:26

    **

    Tested for Laravel 5.8

    **

    Since you wanna get all columns from the table, you can collect all of the data and then filter it using Collections function called Unique

    // Get all users with unique name
    User::all()->unique('name')
    

    or

    // Get all & latest users with unique name 
    User::latest()->get()->unique('name')
    

    For more information you can check Laravel Collection Documentations

    EDIT: You might have issue with perfomance, by using Unique() you'll get all data first from User table, and then Laravel will filter it. This way isn't good if you have lots of Users data. You can use query builder and call each fields that you wanna use, example:

    User::select('username','email','name')->distinct('name')->get();
    

提交回复
热议问题