Add Table Join, Where, and Order By to Views Query in views_query_alter()

别说谁变了你拦得住时间么 提交于 2019-12-03 08:39:09
ummdorian

WHEREs are pretty easy to add once you've got the JOIN in. You can both in a query alter (Drupal 7).

function MODULE_NAME_views_query_alter(&$view, &$query){

// Only alter the view you mean to.
if($view->name == 'VIEW NAME' && $view->current_display == 'DISPLAY'){

    // Create the join.
    $join = new views_join();
    $join->table = 'table_name';
    $join->field = 'entity_id';
    $join->left_table = 'node';
    $join->left_field = 'nid';
    $join->type = 'left';
    // Add the join the the view query.
    $view->query->add_relationship('table_name', $join, 'node');

    // Add the where.
    $view->query->where[1]['conditions'][] = array(
        'field' => 'table_name.collumn_name',
        'value' => 'value',
        'operator' => '='
    );
}}

I found the OP's comments helpful in creating a join in the hook_views_query_alter function, so I wanted to put the parts I found useful in a more digestible answer. I was using Views 2x on Drupal 6x, but I assume it would be very similar to use on D7 Views 2.

The OP mentions describing the relationship of the join in hook_views_table. This wasn't necessary for me, as I was not linking to a custom table, but one that existed in core.

The join creation in the HOOK_views_query_alter() function was very helpful though:


$join = new views_join;
$join->construct('table_name',
        'node',  // left table
        'nid',   // left field
        'nid',   // field
    )

See views_join::construct documentation for more information. In particular, I didn't need to use the 'extra' parameter that the OP used. Perhaps this is necessary with a custom table.

Finally, add the join to the query, and whatever other elements are needed from it:

// Add join to query; 'node' is the left table name
$view->query->add_relationship('table_name',$join,'node');

// Add fields from table (or where clause, or whatever)
$view->query->add_field('table_name','field_name');
...

You already have the $query in parameters, so you can just do:

myhook_views_query_alter(&$view, &$query) {
 if ($view->name = ....) {

  $join = new views_join();
  $join->construct(
    ...
  );

  $query
    ->add_relationship(...)
    ->add_where(...)
    ->add_orderby(...)
    ...
  ;
}

No need to use $view->query->...

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