0

I have a view and in hook_views_pre_execute() I have to add multiple left joins with conditions. Currently I'm doing this:

$or = db_or();
foreach ($fields as $field) {
    $query->leftJoin($field->table, $field->table, '(node.nid = ' . $field->table . '.entity_id)');
    $or = $or->condition($field->table . '.' . $field->field, '%' . $string . '%', 'LIKE');
}

$query->condition($or);

but it doesn't seem to work.

  • inside your "foreach" remove the $or = you're currently only going to get the last $or condition once it exits. – jdu Nov 2 '12 at 15:28
  • While setting $or to the value returned from $or->condition() is not necessary, that is not the reason why the code doesn't work. $or->condition() just returns the pointer to the object that is already in $or. – kiamlaluno Nov 2 '12 at 16:22
  • May you show the code that is executed in hook_views_pre_execute(), including the part you are already showing? – kiamlaluno Nov 2 '12 at 16:23
1

It seems that the problem was $field->field. For example if I have a field called field_book_author in database the $field->table would be field_data_field_book_author and the value of the field would be in field_book_author_value.

So the correct code is:

$or = db_or();
foreach ($fields as $field) {
    $query->leftJoin($field->table, $field->table, '(node.nid = ' . $field->table . '.entity_id)');

    if (property_exists($field, 'additional_fields') && (count($field->additional_fields) > 3)) {
        $field_name = $field->additional_fields[3];
    }else {
        $field_name = $field->field;
    }
    $or->condition($field->table . '.' . $field_name, '%' . $string . '%', 'LIKE');
}

$query->condition($or);
  • Instead of using additional_fields, correct field name can be retrieved from $field->real_name – bogtan Nov 5 '12 at 12:39

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.