简体   繁体   中英

Get max count from laravel eloquent relationship

I have a model Topic which has hasMany relationship with Game 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

 $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

$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

$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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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