在Eloquent中使用groupBy获得每个组更多的行 [英] Getting more rows per group using groupBy in Eloquent
问题描述
我正在尝试编写一个雄辩的查询,该查询每组最多返回3行(使用groupBy)。 此帖子类似,但我不确定如何在此处应用该解决方案。
I'm trying to write an eloquent query which returns up to 3 rows per group (using groupBy). This post is similar but I'm not sure how to apply that solution here.
我有一个雄辩的模型 Deal
用于我的MySQL表交易。每笔交易可以具有四种类型之一
,因此最终应最多包含四组(如果没有某一种类型的交易,则应少于四组
)。
I have an eloquent model Deal
for my MySQL table deal. Each deal can have one of four types
, so ultimately there should be at most four groups (or less if there are no deals of a certain type
).
我尝试了 Deal :: where('status','active')-> groupBy( 'type')-> get();
,这将返回四个对象的数组(四种类型中的每一种对应一个交易),但是我希望每组12个交易,每组3个(它们确实存在于数据库中)。类似地,尝试 Deal :: where('status','active')-> groupBy('type')-> take(3)-> get();
返回一个由三个对象组成的数组(现在缺少一个对象组)。
I have tried Deal::where('status', 'active')->groupBy('type')->get();
and this returns an array of four objects (one deal for each of the four types), however I am expecting 12 deals, 3 per group (and they do exist in the DB). Similarly, trying Deal::where('status', 'active')->groupBy('type')->take(3)->get();
returns an array of three objects (one group is now missing).
到目前为止,我已经通过执行四个单独的数据库查询来完成此操作,每个数据库查询一个四种类型,但如果可以一并完成,我更喜欢它。有什么想法吗?谢谢!
I've accomplished this so far by making four separate DB queries, one for each of the four types but I'd prefer it if this can be done in one. Any thoughts? Thank you!
推荐答案
实现目标的一种方法是:
One of the way you can achieve what you are trying to do is:
Deal:where('status', 'active')
->get()
->groupBy('type')
->map(function($deal) {
return $deal->take(3);
});
当然,您需要检查查询是否返回 null
或 empty
对象,请注意,查询返回所有 active Deal
(s)(过滤发生在 Collection
上),如果有很多 Deal
,这可能是无效的(s)
Of course, you need to check whether the query returns null
or empty
objects and please note that the query returns all the active Deal
(s) (the filtering happens on the Collection
) which might be non-efficient if there are lots of Deal
(s)
这篇关于在Eloquent中使用groupBy获得每个组更多的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!