sql - Laravel Eloquent 按关系计数排序
问题描述
我有一个小型博客应用程序,允许用户上传照片和音频。用户还可以搜索其他博客。在搜索时,我想为我的查询添加一个排名,其优先级如下:
1) Users with most photos
2) Users with most audio
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);
}
博客模型是这样构建的:
public function user()
{
return $this->belongsTo(User::class);
}
我当前的搜索查询:
$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);
根据给定的详细信息,我如何调整我的查询以返回对我的用户照片和音频计数进行排名的博客?
**更新**
我可以通过使用带有急切加载的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);
但是,我怎样才能通过那些嵌套的计数属性来排序这个当前查询呢?
解决方案
基于 Laravel 8 文档: https ://laravel.com/docs/8.x/eloquent-relationships#counting-related-models
您可以尝试:
Blog::withCount(['photos', 'audio'])
它将放置 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);
推荐阅读
- c# - linq中默认填充Select = null
- linux - Linux - 服务器的进程数量有限
- python - 使用 vaex 连接两个数据框
- mysql - 在 MySql 查询中替换“OR EXISTS”,这样我可以获得更好的性能结果
- rest - 如果 Watch 返回的事件很多,Kubernetes Watch API 是否会占用大量内存
- python-3.x - Python ttk组合框中每个项目的悬停提示/工具提示
- python - driver.quit() 和 pkill chrome 释放内存的效果一样吗?
- amazon-web-services - AWS:从站点到站点 VPN 路由流量 --> 特定子网
- javascript - 如何检查消息是否包含其他内容?
- typescript - 使用 `webpack-dev-server` 时可以配置`ts-node` 吗?