Currently the views SQL class 'core/modules/views/src/Plugin/views/query/Sql.php Sql' has limitations in the sense that all joins, order by, group by, expressions, etc must belong to a group or field.
It would be nice to be able to have the same freedom when building/modifying queries as the Select class offers. (core/lib/Drupal/Core/Database/Query/Select.php Select)
eg. there is currently no way to call "addExpression" via hook_views_query_alter.
Yes we can call "addHavingExpression" or "addWhereExpression", however no way to add a select expression that is not related to a field.
Something like this would do the trick
public function addCustomExpression($string, $alias){
$this->customExpressions[] = [
'string' => $string,
'alias' => $alias
];
}
Then when building the query, something like this
protected function compileFields($query) {
if(count($this->customExpressions) > 0){
foreach($this->customExpressions as $ex){
$query->addExpression($ex['string'], $ex['alias']);
}
}
Then of course a programmer may wish to order by this field, so we'd need some sort of custom order by to order by the field. Perhaps something like the below
public function addCustomOrderBy($field, $direction){
$this->customOrderBys[] = [
'field' => $field,
'direction' => $direction
];
}
Then inside the 'compileFields' method.
if(count($this->customOrderBys) > 0){
foreach($this->customOrderBys as $ob){
$query->orderBy($ob->field, $ob->direction);
}
}
}
I understand views is field based, however it would be nice to give developers the freedom to manipulate the sql to their choosing.
Cheers.
Issue fork drupal-2920153
Show commands
Start within a Git clone of the project using the version control instructions.
Or, if you do not have SSH keys set up on git.drupalcode.org:
Comments
Comment #2
Andrew211 commentedComment #4
dravenkComment #5
dravenkI using this way to solve my problem. Hope to help anybody.
Comment #11
scott_euser commentedJust an update on @dravenk's example, here is how the code looks now in D10 + including some WHERE condition examples.
Comment #12
electric.larry commentedThank you @scott_euser and @dravenk for your great examples!
I landed here looking for a way to implement natural sorting of a text field in a view.
My workaround was to use LPAD on the text field and then sort by this field.
Rethinking this problem I ended up with another approach. Instead of prepending the number with endless zeros, I just converted the string value to a number and used this number field for sorting.