简体   繁体   中英

How to select distinct records ordered by date column desc - Laravel

I have such table:

app_id | releaseDate 
111  | 2019-04-21
111  | 2019-05-10
222  | 2019-07-21
222  | 2019-04-22
222  | 2019-05-25
333  | 2019-06-21
333  | 2019-05-21

I need to get such result (need to order desc by releaseDate and after select distinct):

111 | 2019-05-10
222 | 2019-07-21
333 | 2019-06-21

My code:

$apps_histories = ApplicationHistory::with('application')->whereBetween('releaseDate', ['2014-10-01', '2019-10-14'])
            ->orderBy('releaseDate', 'DESC')
            ->groupBy('app_id')
            ->get();

I got:

111 | 2019-04-21
222 | 2019-04-22
333 | 2019-05-21

I have tried different approaches, but I don't get why it's not working as I expect. Could you please help?

Would you please try -

$apps_histories = ApplicationHistory::with('application')
                ->whereBetween('releaseDate', ['2014-10-01', '2019-10-14'])
                ->orderBy('app_id', 'asc')
                ->orderBy('releaseDate', 'desc')
                ->get()
                ->unique('app_id');

EDIT: In my case I am getting a response like this(without application relation):

{
    "0": {
        "app_id": 111,
        "releaseDate": "2019-05-10"
     },
    "2": {
        "app_id": 222,
        "releaseDate": "2019-07-21"
     },
    "5": {
        "app_id": 333,
        "releaseDate": "2019-06-21"
     }
}

You can achieve this behavior in two ways. The first one is to filter releaseDate in the query, using a raw query:

$apps_histories = ApplicationHistory::with('application')
        ->whereBetween('releaseDate', ['2014-10-01', '2019-10-14'])
        ->select(\DB::raw('*, max(releaseDate) as releaseDate'))
        ->orderBy('releaseDate', 'DESC')
        ->groupBy('app_id')
        ->get();

The other way is using unique function in result Collection . Just be aware that this option is not optimized for big result tables:

$apps_histories = ApplicationHistory::with('application')
        ->whereBetween('releaseDate', ['2014-10-01', '2019-10-14'])
        ->orderBy('releaseDate', 'DESC')
        ->get()
        ->unique('app_id');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM