Laravel - Get the last entry of each UID type

后端 未结 6 2006
栀梦
栀梦 2020-11-30 15:46

I have a table that has 100\'s of entries for over 1000 different products, each identified by a unique UID.

ID  UID                 MANY COLUMNS    CREATED          


        
6条回答
  •  囚心锁ツ
    2020-11-30 16:42

    This is easy enough to handle in MySQL:

    SELECT t1.*
    FROM yourTable t1
    INNER JOIN
    (
        SELECT UID, MAX(created_at) AS max_created_at
        FROM yourTable
        GROUP BY UID
    ) t2
        ON t1.UID        = t2.UID AND
           t1.created_at = t2.max_created_at;
    

    Translating this over to Eloquent would be some work, but hopefully this gives you a good starting point.

    Edit: You may want to use a LEFT JOIN if you expect that created_at could ever be NULL and that a given UID might only have null created values.

提交回复
热议问题