【问题标题】:Laravel Eloquent - Only one of a kindLaravel Eloquent - 只有一种
【发布时间】: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

标签: laravel eloquent


【解决方案1】:

你可以试试这个:

public function latest($column = 'created_at')
{
    return $this->orderBy($column, 'desc');
} 
Audit::->latest()->take(2)->get();

【讨论】:

  • take 只是limit 的别名,所以它不会改变任何东西。
  • 你是否尝试使用 latest() 函数?
  • 查看我更新的帖子,希望这个解决方案对您有所帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多