0

I have a table that stores filenames for some files, but each file can be part of a "group", is there a way to make a distinct select so that i get the latest updated record from each of the groups? taking into consideration that even on the same groups the filename is different.

EXAMPLE

filename     group      updated_at
asdwe.pdf    1          2020-08-21 19:38:08
123we.pdf    2          2020-08-21 17:38:08
a34we.pdf    2          2020-08-21 19:38:08
34243.pdf    3          2020-08-21 19:38:08

desired result

asdwe.pdf    1          2020-08-21 19:38:08
123we.pdf    2          2020-08-21 17:38:08
34243.pdf    3          2020-08-21 19:38:08
pato.llaguno
  • 741
  • 4
  • 20
  • Post your query code – STA Aug 26 '20 at 07:40
  • 1
    Does this answer your question? [Laravel - Get the last entry of each UID type](https://stackoverflow.com/questions/49217420/laravel-get-the-last-entry-of-each-uid-type) – xNoJustice Aug 26 '20 at 07:41

2 Answers2

1

I think this will give you desired output. We first group files by their group, then we get only the latest records by the updated_at column:

$files = Model::groupBy('group')->latest('updated_at')->get();
zlatan
  • 3,346
  • 2
  • 17
  • 35
0

You may use distinct as like :.

$q = Model::orderBy('updated_at', 'DESC')
        ->distinct('group')
        ->get();
STA
  • 30,729
  • 8
  • 45
  • 59