Laravel Eloquent 按关系计数排序

Rob*_*man 6 sql relational-database laravel eloquent

我有一个小型博客应用程序,允许用户上传照片和音频。用户还可以搜索其他博客。在搜索时,我想按以下优先级向查询添加排名:

1) Users with most photos
2) Users with most audio
Run Code Online (Sandbox Code Playgroud)

User模型构建如下:

public function blog() {
    return $this->hasOne(Blog::class);
}

public function photos() {
    return $this->hasMany(Photo::class);
}

public function audio() {
    return $this->hasMany(Audio::class);
}
Run Code Online (Sandbox Code Playgroud)

博客模型的构造如下:

public function user()
{
    return $this->belongsTo(User::class);
}
Run Code Online (Sandbox Code Playgroud)

我当前的搜索查询:

    $blogs = Blog::where('description', 'ilike', '%'.$search.'%')
    ->orWhere('title', 'ilike', '%'.$search.'%')
    ->orWhereHas('user', function($query) use ($search) {
        $query->where('name', 'ilike', '%'.$search.'%')
            ->orWhere('username', 'ilike', '%'.$search.'%');
    })
    ->paginate(10);
Run Code Online (Sandbox Code Playgroud)

根据给定的详细信息,我如何调整查询以返回对我的用户照片和音频计数进行排名的博客?

**更新**

我可以通过使用withCount方法和预先加载来获取每个嵌套关系的计数:

    $blogs = Blog::where('description', 'ilike', '%'.$search.'%')
    ->orWhere('title', 'ilike', '%'.$search.'%')
    ->orWhereHas('user', function($query) use ($search) {
        $query->where('name', 'ilike', '%'.$search.'%')
            ->orWhere('username', 'ilike', '%'.$search.'%');
    })
    ->with(['user' => function($query){
        $query->withCount(['blobs', 'audio']);
    }])
    ->paginate(10);
Run Code Online (Sandbox Code Playgroud)

但是,我如何通过这些嵌套计数属性对当前查询进行排序?

小智 6

基于 Laravel 8 文档: https://laravel.com/docs/8.x/eloquent-relationships#counting-lated-models

你可以尝试:

Blog::withCount(['photos', 'audio'])
Run Code Online (Sandbox Code Playgroud)

这将放置 2 列:photos_count 和 audio_count。

所以最终结果将是:

$blogs = Blog::withCount(['photos', 'audio'])
->where('description', 'ilike', '%'.$search.'%')
->orWhere('title', 'ilike', '%'.$search.'%')
->orWhereHas('user', function($query) use ($search) {
    $query->where('name', 'ilike', '%'.$search.'%')
        ->orWhere('username', 'ilike', '%'.$search.'%');
})
->orderBy('photos_count', 'desc')
->orderBy('audio_count', 'desc')
->paginate(10);
Run Code Online (Sandbox Code Playgroud)