laravel - 按大多数视图对结果进行排序
问题描述
我有来自“items”表的结果,它与“items_views”表相关联,它记录了每个视图。
我想按我的这段代码中的大多数视图对结果进行排序,我知道有一些简单的东西,但我找不到正确的语法,我也无法在文档中找到它。
$items = Items::whereHas('category', function ($query) {
$query->where('status', 1); // only where the category it belongs to is active
})->whereHas('hot', function ($query) { // "hot" is the relationship with the "Items_views" model
$query->orderBy('item_id_count', 'desc'); <-- EXAMPLE
})->whereHas('user', function ($query) {
$query->where('access', 1); // only by users with a public profile
})->where('visible', 1)
->where('status', 1)
->orderByDesc('id')
->paginate(25);
编辑:
我的数据库表:
Items: id, user_id ecc
Items_views: id, item_id, user_id ecc
我的模型:
- 项目.php
- ItemsViews.php
这是插入“Items.php”中的关系
public function hot(){
return $this->belongsTo(ItemsViews::class);
}
解决方案
如果 item 和 item_views 表之间存在一对多关系,那么您需要将映射更正为
public function hot(){
return $this->hasMany(ItemsViews::class);
}
然后您可以withCount
在您的查询中使用并使用视图数对您的结果进行排序
$items = Items::withCount('hot')
->whereHas('category', function ($query) {
$query->where('status', 1);
})->whereHas('user', function ($query) {
$query->where('access', 1);
})->where('visible', 1)
->where('status', 1)
->orderByDesc('hot_count')
->paginate(25);
推荐阅读
- java - Android 应用程序中实现的语言更改不起作用
- java - 通知栏架构中的音乐播放器
- java - 共享使用时的 java.util.Random.nextX 分布
- reactjs - ReactJS 中的克隆元素
- python - 闰年检查器未通过未知测试用例
- python - 为什么ndarray打印不一致?
- php - 查询未执行 Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter number: 绑定变量数与标记数不匹配
- c++ - 如何优雅地将长类型名称传递给模板参数?
- angular - 如何绑定角度动态形式?
- amazon-ec2 - Terraform & Ansible 控制器和私钥分发