Adding a JOIN statement in hook_views_query_alter()

烂漫一生 提交于 2020-02-24 08:54:21

问题


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?


回答1:


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 :/




回答2:


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');
}


来源:https://stackoverflow.com/questions/3134941/adding-a-join-statement-in-hook-views-query-alter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!