首页 > 解决方案 > Laravel distinct/groupBy 和分页

问题描述

我有一个Certificate包含以下列的模型:codenumbertypedateversion等。

此证书可以更新,我想使用该version列跟踪这些更新。基本上,我想保留所有证书,但在列表页面上,我只想显示一次,并且可能显示特定记录有 x 个版本并且只显示最后一个。

前任。(id、代码、编号、类型、日期、版本)

1, x1, num1, internal, 01.01.2020, 1
2, x2, num2, external, 01.03.2020, 1
3, x3, num3, external, 02.03.2020, 1
4, x4, num2, internal, 05.01.2020, 2

基本上,带有 number 的记录num2有一个较新的版本,因此列表应该只显示 3 条记录,对于带有 number 的记录num2,将显示最后一条记录(id 4)。

最后,这些记录可能很多,所以我想对它们进行分页。

实现这一目标的最佳/有效方式是什么?

我知道有很多关于groupBy我也是第一件事的讨论,但似乎groupBy不是我的情况的选择,但仅在尝试仅按聚合值(计数、日期、最大值等)分组时。

我发现的第二个选项是使用distinct我找到的方法,我almost there之所以这么说是因为我无法按单个列进行过滤,也无法显示其余列。

前任:

$certificates = Certificate::select('number', 'type', 'code', 'date')->distinct('number')->get(); 
// will display the duplicates too.


$certificates = Certificate::select('number')->distinct('number')->get(); 
//returns the correct records (withoud duplicates) but I lose the access to other (code, type... ) columns.

请注意,这应该保留为 Query Builder/Eloquent 以便能够使用分页,所以我认为转换为集合是不行的。

还是有另一种更好的解决方案来实现这种行为?

标签: mysqllaraveleloquentquery-builder

解决方案


推荐阅读