Archivi tag: views query alter

How to add a join relationship in views query alter

This post is a personal reminder for a task not so easy to do: add a join in hook_views_query_alter.

So that’s the solution I’ve found for Drupal 7:

/**
 * Implements hook_views_query_alter().
 */
function mymodule_views_query_alter(&$view, &$query) {
	if ($view->name == 'my_view_machine_name') {
		$join = new views_join();
		$join->construct('my_table_name', 'left_table_name', 'left_table_field_name', 'my_table_field_name');
		$query->add_relationship('my_table_alias', $join, 'my_table_name');
	}
}

And this is an example with real variables:

/**
 * Implements hook_views_query_alter().
 */
function mymodule_views_query_alter(&$view, &$query) {
	if ($view->name == 'authors_view') {
		$join = new views_join();
		$join->construct('users', 'node', 'uid', 'uid');
		$query->add_relationship('authors', $join, 'users');
	}
}
Annunci
Contrassegnato da tag , ,
%d blogger hanno fatto clic su Mi Piace per questo: