mysql - Laravel distinct/groupBy 和分页
问题描述
我有一个Certificate
包含以下列的模型:code
、number
、type
、date
、version
等。
此证书可以更新,我想使用该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 以便能够使用分页,所以我认为转换为集合是不行的。
还是有另一种更好的解决方案来实现这种行为?
解决方案
推荐阅读
- java - 两个 LocalDate 对象之间的周期计算似乎已关闭
- c++ - 实例正确声明
- hive - 如何使用 python 连接到 HIVE?
- reactjs - React 和 Jest - 使用 PropTypes.instanceOf 测试组件
- python - 创建后使用 Button 将 HBox 添加到 VBox
- javascript - 如何将 React 组件连接到 Laravel Blade
- angular - Angular 8:router.navigate,跳过状态更改但保持“历史步骤”
- python - 遍历一个函数返回包含两个列表的 2 元组?
- php - 为什么我无法从 Jquery 获取价值到 php?
- r - 独立于出现顺序计算 Bigrams