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

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

    For those who like me doing same mistake. Here is the elaborated answer Tested in Laravel 5.7

    A. Records in DB

    UserFile::orderBy('created_at','desc')->get()->toArray();

    Array
    (
        [0] => Array
            (
                [id] => 2073
                [type] => 'DL'
                [url] => 'https://i.picsum.photos/12/884/200/300.jpg'
                [created_at] => 2020-08-05 17:16:48
                [updated_at] => 2020-08-06 18:08:38
            )
    
        [1] => Array
            (
                [id] => 2074
                [type] => 'PROFILE'
                [url] => 'https://i.picsum.photos/13/884/200/300.jpg'
                [created_at] => 2020-08-05 17:20:06
                [updated_at] => 2020-08-06 18:08:38
            )
    
        [2] => Array
            (
                [id] => 2076
                [type] => 'PROFILE'
                [url] => 'https://i.picsum.photos/13/884/200/300.jpg'
                [created_at] => 2020-08-05 17:22:01
                [updated_at] => 2020-08-06 18:08:38
            )
    
        [3] => Array
            (
                [id] => 2086
                [type] => 'PROFILE'
                [url] => 'https://i.picsum.photos/13/884/200/300.jpg'
                [created_at] => 2020-08-05 19:22:41
                [updated_at] => 2020-08-06 18:08:38
            )
    )
    

    B. Desired Grouped result

    UserFile::select('type','url','updated_at)->distinct('type')->get()->toArray();

    Array
    (
        [0] => Array
            (
                [type] => 'DL'
                [url] => 'https://i.picsum.photos/12/884/200/300.jpg'
                [updated_at] => 2020-08-06 18:08:38 
            )
    
        [1] => Array
            (
                [type] => 'PROFILE'
                [url] => 'https://i.picsum.photos/13/884/200/300.jpg'
                [updated_at] => 2020-08-06 18:08:38
            )
    )
    

    So Pass only those columns in "select()", values of which are same. For example: 'type','url'. You can add more columns provided they have same value like 'updated_at'.

    If you try to pass "created_at" or "id" in "select()", then you will get the records same as A. Because they are different for each row in DB.

提交回复
热议问题