[英]Get max count from laravel eloquent relationship
I have a model Topic which has hasMany relationship with Game model.我有一个 model主题,它与游戏model 有很多关系。
//Topic.php
public function Games() {
return $this->hasMany(Game::class);
}
//Game.php
public function Topic() {
return $this->belongsTo(Topic::class);
}
What I need is getting the Topic which has the max count (also the count value) of Games based on 'created_at' today,this week,this month etc. I tried the following code, but the nested whereBetween query does not work, instead it is showing all the related topic->games created ever我需要的是根据今天、本周、本月等“created_at”获得游戏的最大计数(也是计数值)的主题。我尝试了以下代码,但嵌套的 whereBetween 查询不起作用,而是它显示了所有相关的主题->曾经创建的游戏
$top_topic_month = Topic::with('games')->get()->sortBy(function($q)
{
return $q->games->whereBetween('created_at',[today()->startOfMonth, today()])->count();
})->first();
$top_topic_month_count = ?
try this试试这个
use withCount
to generate games_count
使用
withCount
生成games_count
$top_topic_month = Topic::withCount('games')->whereHas('games',function($q) use($startMonth){
$q->whereBetween('created_at', [$startMonth, today()]);
})->orderByDesc('games_count')->first();
$top_topic_month_count = $top_topic_month->count()
With the help of the above answer from @kamlaesh Paul, I finally got the below code working for me在@kamlaesh Paul 的上述回答的帮助下,我终于得到了下面的代码为我工作
$top_topic_month = Topic::withCount('games')->whereHas('games',function($q) use($startMonth){
$q->whereBetween('created_at', [$startMonth, today()]);
})->orderByDesc('games_count')->first();
$top_topic_month_count = $top_topic_month->count()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.