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.