Laravel - 获取每个 UID 类型的最后一个条目 [英] Laravel - Get the last entry of each UID type

查看:14
本文介绍了Laravel - 获取每个 UID 类型的最后一个条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表格,其中包含 1000 多种不同产品的 100 个条目,每个条目都由唯一的 UID 标识.

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 AT
1   dqwdwnboofrzrqww1   ...             2018-02-11 23:00:43
2   dqwdwnboofrzrqww1   ...             2018-02-12 01:15:30

3   dqwdwnbsha5drutj5   ...             2018-02-11 23:00:44
4   dqwdwnbsha5drutj5   ...             2018-02-12 01:15:31

5   dqwdwnbvhfg601jk1   ...             2018-02-11 23:00:45
6   dqwdwnbvhfg601jk1   ...             2018-02-12 01:15:33

...

我希望能够获得每个 UID 的最后一个条目.

I want to be able to get the last entry for each UID.

ID  UID                 MANY COLUMNS    CREATED AT
2   dqwdwnboofrzrqww1   ...             2018-02-12 01:15:30
4   dqwdwnbsha5drutj5   ...             2018-02-12 01:15:317
6   dqwdwnbvhfg601jk1   ...             2018-02-12 01:15:33

这可以在一次数据库调用中实现吗?

Is this possible in one DB call?

我尝试过使用 DB 和 Eloquent,但到目前为止我要么得到零结果,要么得到表格的全部内容.

I have tried using DB as well as Eloquent but so far I either get zero results or the entire contents of the Table.

安迪

推荐答案

这在 MySQL 中很容易处理:

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;

将其转换为 Eloquent 需要一些工作,但希望这可以为您提供一个好的起点.

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

如果您希望 created_at 永远是 NULL and,您可能想要使用 LEFT JOIN> 给定的 UID 可能只有 null 创建的值.

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.

这篇关于Laravel - 获取每个 UID 类型的最后一个条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆