繁体   English   中英

从 laravel eloquent 关系中获取最大计数

[英]Get max count from laravel eloquent relationship

我有一个 model主题,它与游戏model 有很多关系。

 //Topic.php

 public function Games() {
    return $this->hasMany(Game::class);
}


 //Game.php

 public function Topic() {
    return $this->belongsTo(Topic::class);
}

我需要的是根据今天、本周、本月等“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 = ? 

试试这个

使用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()

在@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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM