Skip to content

Commit c8750d4

Browse files
authored
Merge pull request #4788 from Laravel-Backpack/always-use-the-selectRaw-expressions
Don't exclude raw expression columns
2 parents ec7fe8f + b6b12de commit c8750d4

File tree

1 file changed

+18
-1
lines changed

1 file changed

+18
-1
lines changed

src/app/Library/CrudPanel/Traits/Query.php

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -242,13 +242,30 @@ private function getCountFromQuery(Builder $query)
242242
// add the count query in the "outer" query.
243243
$outerQuery = $outerQuery->selectRaw('count(*) as total_rows');
244244

245+
// Expression columns are hand-written by developers in ->selectRaw() and we can't exclude those statements reliably
246+
// so we just store them and re-use them in the sub-query too.
247+
$expressionColumns = [];
248+
249+
foreach ($crudQuery->columns as $column) {
250+
if (! is_string($column) && is_a($column, 'Illuminate\Database\Query\Expression')) {
251+
$expressionColumns[] = $column;
252+
}
253+
}
245254
// add the subquery from where the "outer query" will count the results.
246255
// this subquery is the "main crud query" without some properties:
247256
// - columns : we manually select the "minimum" columns possible from database.
248257
// - orders/limit/offset because we want the "full query count" where orders don't matter and limit/offset would break the total count
249258
$subQuery = $crudQuery->cloneWithout(['columns', 'orders', 'limit', 'offset']);
250259

251-
$outerQuery = $outerQuery->fromSub($subQuery->select($modelTable.'.'.$this->model->getKeyName()), str_replace('.', '_', $modelTable).'_aggregator');
260+
// select only one column for the count
261+
$subQuery->select($modelTable.'.'.$this->model->getKeyName());
262+
263+
// in case there are raw expressions we need to add them too.
264+
foreach ($expressionColumns as $expression) {
265+
$subQuery->selectRaw($expression);
266+
}
267+
268+
$outerQuery = $outerQuery->fromSub($subQuery, str_replace('.', '_', $modelTable).'_aggregator');
252269

253270
return $outerQuery->cursor()->first()->total_rows;
254271
}

0 commit comments

Comments
 (0)