Laravel雄辩-只有一种

时间:2019-04-01 12:57:32

标签: laravel eloquent

我正在使用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,但是在雄辩的模型上不可能(直接),对吧?

1 个答案:

答案 0 :(得分:0)

您可以尝试以下方法:

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