Laravel 获取每个组的最新记录
问题描述
我正在尝试将一些原始 SQL 迁移到模型上的 Eloquent(或查询生成器)范围.我的零件历史记录表如下所示:
I am trying to migrate some Raw SQL to an Eloquent (or Query Builder) scope on my model. My Parts history table looks like this:
请注意,同一个 part_id 可以有多个状态相同的条目.
Notice the same part_id can have multiple entries where the status is the same.
目前我使用以下选择最新状态:
At the moment I use the following to select the latest status:
我正在尝试在零件模型上制作一个范围,到目前为止我有这个:
I am trying to make a scope on the parts model out of this, so far I have this:
这是其中的一部分(但仍然使用一些原始 SQL),我就是想不通其余的
which is part way there (but still using some raw SQL), I just can't figure out the rest
推荐答案
您可以将查询重写为左连接以获得相同的结果
You could rewrite your query as left join to get the same results
我猜你可以在你的范围内轻松转换上面的查询,比如
and I guess you can transform easily above query in your scope something like
Laravel Eloquent 选择具有最大值的所有行created_at
Laravel - 获取最后一个条目每种 UID 类型
Laravel Eloquent 按最近记录分组
使用上述查询作为 has
关系进行编辑,要获取每个部分的最新历史记录,您可以定义一个 hasOne
关系,如
Edit using above query as has
relation,To get the latest history for each part you can define a hasOne
relation like
然后要加载具有最新历史记录的零件,您可以将上面定义的映射加载为
And then to load parts with their latest history you could eager load above defined mapping as
您将拥有一份零件清单以及最新的历史记录
You will have a list of parts along with latest history as
这篇关于Laravel 获取每个组的最新记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!