Score:6

What method should I use instead of Drupal\Core\Entity\Query\Sql\Query::addExpression()?

my flag

I am using Entity Query to select nodes of two different types. The fetching seems to be working, but I to sort the returned values. Both the content types have different date fields. I know I could do this with $query->addExpression('COALESCE( field_date_1, field_date_2)', 'Date'); $query->sort('Date', 'DESC'); but addExpression() isn't an existing method, and the code throws this exception.

Error: Call to undefined method Drupal\Core\Entity\Query\Sql\Query::addExpression()

How can I sort on more than 2 date fields?

Score:6
cn flag

Entity queries don't support expressions. To get it around it, add a tag to the query:

$query->addTag('mymodule');

Then implement hook_query_alter(), check for the tag, and add the expression there instead:

function mymodule_query_alter(Drupal\Core\Database\Query\AlterableInterface $query) {
  if ($query instanceof Drupal\Core\Database\Query\SelectInterface && $query->hasTag('mymodule')) {
    $query->addExpression('...');
  }
}
Akansha avatar
my flag
Thanks, it worked and hook_query_TAG_alter() too works here. Adding for future references.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.