3

I need to modify a query Views generates so that I can use highly custom filters. I have implemented the add_where() function with some ORs thanks to this question: OR operator in Drupal View Filters

However this only solves a part of my problem. There are some fields that I cannot filter on because I need to have extra JOINs in my query.

Is there something along the lines of

$view->query->add_where()

that can insert JOIN statements?

3
  • Well, there is $view->query->add_table() and $view->query->add_relationship(), but their usage, relation and preconditions are not obvious from the code (at least not for me). Can't you just add the relationships via the Views UI to ensure that your needed tables get joined in? Commented Jun 28, 2010 at 23:38
  • @Henrik After digging into the query.inc file in the views module, I found the functions you mentioned. There isn't much to go on aside from the comments, so usage is somewhat vague. Also, make your comment an answer so i can accept it. Commented Jul 1, 2010 at 14:24
  • Yup, usage is not obvious, and the documentation is lacking - I have not tried to use them either, so I can not really help with that. Turned comment to answer as suggested - thanks. Commented Jul 1, 2010 at 18:08

2 Answers 2

5

I found an answer here. Shameless copy:

function hook_views_query_alter(&$view, &$query) {
    $join = new views_join();
    $join->table = 'my_table';
    $join->field = 'my_field';
    $join->left_table = 'left_table';
    $join->left_field = 'left_field';
    $join->type = 'left';
    $join->extra = array(
        array(
            'field' => 'bundle',
            'value' => 'user',
        )
    );
    $query->add_relationship('relationship_name', $join, 'node');
}
Sign up to request clarification or add additional context in comments.

Comments

2

Well, there is $view->query->add_table() and $view->query->add_relationship() (in the views_query class in 'includes/query.inc'), but their usage, relation and preconditions are not obvious from the code (at least not for me).

Maybe you could add the relationships via the Views UI to ensure that your needed tables get joined in.


(Note: Comment turned to answer, as no better idea showed up :/

1 Comment

Actually, adding another relationship in the views UI did work for me. All I had to do was look at the generated query from views to find out what table was needed to go into the add_where function. hooray!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.