在某些条件下使用 withCount 方法

Use withCount method with some condition

我有一个 musics_rate table 和一个 musics table:

musics_rate:
    music_id : integer
    user_id : integer
    rate_type : boolean

音乐模型:

public function rates()
{
    return $this->belongsToMany(User::class, 'musics_rate');
}

现在我想按 music_ratesmusics 进行排序,其中 rate_type==true 计数(本周创建):

Music::where('created_at','>=', Carbon::parse('last saturday'))
    ->withCount('rates')
    ->orderby('rates_count','desc')
    ->get();

但它按所有比率(正比率和负比率)计数排序。

有没有办法只过滤正利率。

如果您只想要 music 个具有正 rate 的模型:

Music::whereHas('rates', function ($q) {
    $q->where('rate_type', true);
})
    ->where('created_at', '>=', Carbon::parse('last saturday'))
    ->withCount('rates')
    ->orderby('rates_count', 'desc')
    ->get();

如果您想要所有 music 模型但只加载正数 rates:

Music::with([
    'rates' => function ($q) {
        $q->where('rate_type', true);
    }
])
    ->where('created_at', '>=', Carbon::parse('last saturday'))
    ->withCount('rates')
    ->orderby('rates_count', 'desc')
    ->get();