0

I was stucked making a few tweaks to a view trying to do the following. In mysql exists the possibility to use WHERE IF to evaluate some variable/operation to apply differents conditions depending on the result/value, like a common IF/ELSE block, is there any way to do it with add_where() or any other similar method? I need to apply a WHERE condition to the query when the value of a variable called $scope is G and a different when its L, there's any way to achieve that?

What I need to do is to do this query on Drupal 7 Views hooks

SELECT * FROM tbl1 AS t1 JOIN tbl2 AS t2 ON t2.entity_id = t1.nid JOIN tbl3 AS t3 ON t3.entity_id = t1.uid  WHERE t1.status = 1 AND t1.type = "article" AND IF(t2.field_alcance_nodo_value = '{char}', t3.field_pais_usuario_value = '{string}', t3.field_pais_usuario_value LIKE '%') ORDER BY t1.changed DESC;

but I'm stucked on the IF part... I'm using the hook_views_query_alter() but I don't know if it's enough.

Thank you in advance,

1 Answer 1

1

You can achieve this using switch-case or if-else in mymodule_views_query_alter.

function mymodule_views_query_alter(&$view, &$query) {
  //Get your variable $scope here
  switch($scope) {
    case 'G':
      $query->add_where_expression(0, "$variable = :placeholder", array(':placeholder' => 'value');      
      break;
    case 'L':
      $query->add_where_expression(0, "$another_variable = :another_placeholder", array(':another_placeholder' => 'another_value');      
      break;
  }
}

Hope this helps.

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.