【问题标题】:Use withCount method with some condition在某些条件下使用 withCount 方法
【发布时间】:2019-11-14 20:27:25
【问题描述】:

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

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

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

有没有办法只过滤正率。

【问题讨论】:

  • 可以添加where条件

标签: laravel laravel-5 eloquent lumen laravel-5.8


【解决方案1】:

如果您只想要具有正面ratemusic 模型:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-17
    • 2019-11-16
    • 1970-01-01
    • 2017-02-17
    • 2020-12-07
    • 2012-06-03
    • 1970-01-01
    相关资源
    最近更新 更多