【发布时间】:2019-04-01 12:57:32
【问题描述】:
我正在使用https://github.com/owen-it/laravel-auditing,它将每个模型(使用特殊特征)的每次更改记录到一个名为audits的表中:
id-
auditable_type= 已更改模型类的名称 -
auditable_id= 已更改模型的 ID -
created_at= 更改日期 - ...
使用以下示例数据:
| id | auditable_type | auditable_id | created_at |
|----|----------------|--------------|------------|
| 1 | App\City | 1 | 2019-01-01 |
| 2 | App\City | 2 | 2019-01-02 |
| 3 | App\City | 2 | 2019-01-02 |
现在我想查询所有模型的两个最新变化(order by created_at DESC),这很容易:
Audit::query()
->limit(2)
->orderBy("created_at", "DESC")
->get()
这将导致:
| id | auditable_type | auditable_id | created_at |
|----|----------------|--------------|------------|
| 2 | App\City | 2 | 2019-01-02 |
| 3 | App\City | 2 | 2019-01-02 |
但是如何获取最新更改的模型行,而不是最新更改:
| id | auditable_type | auditable_id | created_at |
|----|----------------|--------------|------------|
| 1 | App\City | 1 | 2019-01-01 |
| 3 | App\City | 2 | 2019-01-02 |
通常,我会使用 GroupBy,但在 eloquent 模型上这是不可能的(直接),对吧?
【问题讨论】:
-
您可以将 groupBy 与查询生成器一起使用...
groupBy('auditable_type', 'auditable_id') -
是的,您可以在集合上使用
groupBy。如Laravel documentation 所示。您还可以在查询生成器上groupBy,如here 所示。 -
你的数据库服务器支持窗口函数吗? en.wikipedia.org/wiki/SQL_window_function
-
@devon 和@swonder:这是我的第一个猜测,但后来我得到了
this is incompatible with sql_mode=only_full_group_by错误。 -
@michail1982:不。 MySQL 5.7