【问题标题】:Eloquent get last record groupped by dateEloquent 获取按日期分组的最后一条记录
【发布时间】:2021-10-18 12:15:15
【问题描述】:

我有一个表 prices ,我在其中存储了一天中更多的时间,更多的值引用了 customer,如下所示:

prices

| id | customer_id | value_1 | value_2 | value_3 |      created_at      |
-------------------------------------------------------------------------
| 1  |     10      | 12345   |    122   |    10  |  2021-08-11 10:12:40 |
| 2  |     10      | 22222   |    222   |    22  |  2021-08-11 23:56:20 |
| 3  |     12      | 44444   |    444   |    44  |  2021-08-12 08:12:10 |
| 4  |     10      | 55555   |    555   |    55  |  2021-08-13 14:11:20 |
| 5  |     10      | 66666   |    666   |    66  |  2021-08-13 15:15:30 |
| 6  |     10      | 77777   |    777   |    77  |  2021-08-13 16:12:50 |

我在该表上有一些过滤器,仅检索日期大于 X 和/或小于 Y 的记录,按 value_1 或 value_2 对记录进行排序,等等... 使用该过滤器,我只需为指定客户的每一天获取 1 条记录。 例如,我可以通过使用 sql 函数 max() 并按日期分组来获得 value_1 最高的记录。

// Init query
$query = Price::query();
// Take the greatest value of value1
$query = $query->selectRaw(
    'max(value_1) as highest_value_1, ' .
    'date(created_at) as date'
);

// If defined, add a greater or equals
if ($from) $query->where("created_at", ">=", $from);

// If defined add a lower or equals
if ($to) $query->where("created_at", "<=", $to);

// Get results for current customer only, grupping by date and ordering it
$query = $query->where('customer_id', $id)->groupBy('date')
    ->orderBy('date', 'DESC');
// Fetch records
$records = $query->get();

但现在我希望只指定客户每天的最后一条记录

我需要一个 eloquent/sql 解决方案,因为要搜索的日期范围可能很大,而且表中有很多记录。

我该如何存档? 谢谢

【问题讨论】:

    标签: php sql database laravel eloquent


    【解决方案1】:

    不是一个完整的解决方案(没有客户过滤器或 laravel 使用),但我会在纯 sql 中使用类似的东西:

    SELECT 
      CONCAT(EXTRACT(YEAR_MONTH FROM created_at),EXTRACT(DAY FROM created_at)) AS day, 
      MAX(created_at) 
    FROM mytable 
    GROUP BY day;
    

    当然,您可以使用其他函数来按天分组(如字符串正则表达式或子字符串)。

    【讨论】:

    • 您好 Armage,抱歉回复晚了,感谢您的回复!使用您的代码,我可以得出与我相同的结果:我使用了DATE() 函数,而不是使用CONCAT() 函数。以这种方式,我返回最后记录的所有日期值,但我没有该记录的值:您知道如何获取所选记录的所有其他属性,例如 idvalue_2?谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-13
    • 2020-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多