php - 如何在 eloquent 的多个关系字段上使用 count 和 orderBy?
问题描述
我要做的是为表数据设置服务器端配置。所以我有一个模型CounterLog
,它有 3 个关系集 [ belongsTo
] category
, location
, user
. 我想要一个查询来过滤所有CounterLog
数据,包括关系、withoffset
和limit
方法orderBy
集,同时检索所有过滤后的行,忽略offset
and limit
。这是我到目前为止所管理的,也许可以更好地理解我想要的东西:
$search_query = function($q) use ($search) {
$q->where('name', 'like', '%' . $search . '%');
};
$query = CounterLog::where('created_at', 'like', '%' . $search . '%')
->orWhereHas('category', $search_query)
->orWhereHas('location', $search_query)
->orWhereHas('user', $search_query);
$logs = $query->offset($offset)->limit($limit)->get();
$logs_total = $query->offset(0)->count();
在我使用的最后一行中,$query->offset(0)
因为某种原因 ifoffset
设置为一个数字$logs_total
变为 0。我不确定这是不是正确的方法..但即使这样我也不知道如何使用orderBy
for ex。category.name
.
我知道我总是可以在 eloquent 中使用原始查询,但我想知道是否有办法使用 ORM 和关系。如果您能帮我解决这个问题,我将不胜感激……因为斗争是真实的。
非常感谢 :)
显然我还没有使用 ORM 的解决方案,所以我使用“原始”查询来解决:
$query = $this->db->table('counter_logs')
->leftJoin('categories', 'counter_logs.category_id', '=', 'categories.id')
->leftJoin('locations', 'counter_logs.location_id', '=', 'locations.id')
->leftJoin('users', 'counter_logs.user_id', '=', 'users.id');
->where('counter_logs.created_at', 'like', '%' . $search . '%')
->orWhere('categories.name', 'like', '%' . $search . '%')
->orWhere('locations.name', 'like', '%' . $search . '%')
->orWhere('users.name', 'like', '%' . $search . '%');
->select('counter_logs.id as id', 'categories.name as category', 'locations.name as location', 'users.name as user', 'counter_logs.created_at as date');
$json['total'] = $query->count();
$logs = $query->offset($offset)->limit($limit)->orderBy($sort, $order)->get();
解决方案
尝试交换语句:
$logs_total = $query->count();
$logs = $query->offset($offset)->limit($limit)->get();
或克隆基本查询,如下所示:
$total_count_query = clone $query;
$logs = $query->offset($offset)->limit($limit)->get();
$logs_total = $total_count_query->count();
推荐阅读
- python - Matplotlib 在查看后自动关闭绘图/图形
- azure - 无需客户端证书即可访问 Service Fabric Explorer
- sql-server - 如何从存储过程中获取唯一标识符?
- react-native - react-native 更新用户位置
- lighthouse - 有什么方法可以获得性能摘要结果(脚本、渲染、空闲时间)?
- python-3.x - 如何在 Keras 网络模型中调整 3D 卷的大小?
- c# - 参数 1 无法从类转换为 IWebDriver
- java - 如何使用扫描仪检查 Zip 文件是否由 CSV 或 JAVA 中的其他类型文件压缩?
- c++ - 从数字数组中删除重复项
- generics - 如何在 UML 中对依赖于属性的接口实现建模?