2

Is there any way to query by dynamically calculated values using Entity Field Query? Take the following:

I want to query where the sum of field_some_number and a user-provided variable are greater than or equal to 5. Right now I'm only able to do the following:

$my_variable = -7;    
$query->fieldCondition('field_some_number', 'value', 5, '>=');

But obviously this doesn't include my user-provided variable. How can I calculate this on the fly? Could hook-query-alter help me with this? I have not been able to figure out how to properly implement it. I'm using this with the Restful-Drupal module.

0

I don't think Entity Query supports expression.

  • In your case, I think you might not even need it as you can workaround.

    $value_to_compare = 5 - $user_provided_value; $query->fieldCondition('field_some_number', 'value', $value_to_compare, '>=');

  • But if you need to compute value based on columns of database table, you can go ahead with db_select, where you can have addExpression for calculation.

    $query->addExpression('table_columns_1 + table_columns_2', 'sum'); $query->having('sum', 5,'>=');

  • Makes sense, was hoping to stick with EFQ. Also, my example might not have been the best, but imagine you wanted a more complex query where field_some_number * field_another_number >= 50. Is there any way to combine db_select with EFQ or do I need a totally new query? – mjoyce91 Sep 30 '16 at 14:11
  • total new query – arpitr Oct 1 '16 at 4:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.