【发布时间】: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