簡體   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