3 namespace Drupal\views\Plugin\views\relationship;
5 use Drupal\Core\Database\Query\AlterableInterface;
6 use Drupal\Core\Form\FormStateInterface;
7 use Drupal\views\Views;
8 use Drupal\views\Entity\View;
11 * Relationship handler that allows a groupwise maximum of the linked in table.
12 * For a definition, see:
13 * http://dev.mysql.com/doc/refman/5.0/en/example-maximum-column-group-row.html
14 * In lay terms, instead of joining to get all matching records in the linked
15 * table, we get only one record, a 'representative record' picked according
16 * to a given criteria.
19 * Suppose we have a term view that gives us the terms: Horse, Cat, Aardvark.
20 * We wish to show for each term the most recent node of that term.
21 * What we want is some kind of relationship from term to node.
22 * But a regular relationship will give us all the nodes for each term,
23 * giving the view multiple rows per term. What we want is just one
24 * representative node per term, the node that is the 'best' in some way:
25 * eg, the most recent, the most commented on, the first in alphabetical order.
27 * This handler gives us that kind of relationship from term to node.
28 * The method of choosing the 'best' implemented with a sort
29 * that the user selects in the relationship settings.
31 * So if we want our term view to show the most commented node for each term,
32 * add the relationship and in its options, pick the 'Comment count' sort.
34 * Relationship definition
35 * - 'outer field': The outer field to substitute into the correlated subquery.
36 * This must be the full field name, not the alias.
37 * Eg: 'term_data.tid'.
39 * 'argument field': These options define a views argument that the subquery
40 * must add to itself to filter by the main view.
41 * Example: the main view shows terms, this handler is being used to get to
42 * the nodes base table. Your argument must be 'term_node', 'tid', as this
43 * is the argument that should be added to a node view to filter on terms.
45 * A note on performance:
46 * This relationship uses a correlated subquery, which is expensive.
47 * Subsequent versions of this handler could also implement the alternative way
48 * of doing this, with a join -- though this looks like it could be pretty messy
49 * to implement. This is also an expensive method, so providing both methods and
50 * allowing the user to choose which one works fastest for their data might be
52 * If your use of this relationship handler is likely to result in large
53 * data sets, you might want to consider storing statistics in a separate table,
54 * in the same way as node_comment_statistics.
56 * @ingroup views_relationship_handlers
58 * @ViewsRelationship("groupwise_max")
60 class GroupwiseMax extends RelationshipPluginBase {
65 protected function defineOptions() {
66 $options = parent::defineOptions();
68 $options['subquery_sort'] = ['default' => NULL];
69 // Descending more useful.
70 $options['subquery_order'] = ['default' => 'DESC'];
71 $options['subquery_regenerate'] = ['default' => FALSE];
72 $options['subquery_view'] = ['default' => FALSE];
73 $options['subquery_namespace'] = ['default' => FALSE];
81 public function buildOptionsForm(&$form, FormStateInterface $form_state) {
82 parent::buildOptionsForm($form, $form_state);
84 // Get the sorts that apply to our base.
85 $sorts = Views::viewsDataHelper()->fetchFields($this->definition['base'], 'sort');
87 foreach ($sorts as $sort_id => $sort) {
88 $sort_options[$sort_id] = "$sort[group]: $sort[title]";
90 $base_table_data = Views::viewsData()->get($this->definition['base']);
92 // Extends the relationship's basic options, allowing the user to pick a
93 // sort and an order for it.
94 $form['subquery_sort'] = [
96 '#title' => $this->t('Representative sort criteria'),
97 // Provide the base field as sane default sort option.
98 '#default_value' => !empty($this->options['subquery_sort']) ? $this->options['subquery_sort'] : $this->definition['base'] . '.' . $base_table_data['table']['base']['field'],
99 '#options' => $sort_options,
100 '#description' => $this->t("The sort criteria is applied to the data brought in by the relationship to determine how a representative item is obtained for each row. For example, to show the most recent node for each user, pick 'Content: Updated date'."),
103 $form['subquery_order'] = [
105 '#title' => $this->t('Representative sort order'),
106 '#description' => $this->t("The ordering to use for the sort criteria selected above."),
107 '#options' => ['ASC' => $this->t('Ascending'), 'DESC' => $this->t('Descending')],
108 '#default_value' => $this->options['subquery_order'],
111 $form['subquery_namespace'] = [
112 '#type' => 'textfield',
113 '#title' => $this->t('Subquery namespace'),
114 '#description' => $this->t('Advanced. Enter a namespace for the subquery used by this relationship.'),
115 '#default_value' => $this->options['subquery_namespace'],
119 // WIP: This stuff doesn't work yet: namespacing issues.
120 // A list of suitable views to pick one as the subview.
121 $views = ['' => '- None -'];
122 foreach (Views::getAllViews() as $view) {
123 // Only get views that are suitable:
124 // - base must the base that our relationship joins towards
125 // - must have fields.
126 if ($view->get('base_table') == $this->definition['base'] && !empty($view->getDisplay('default')['display_options']['fields'])) {
127 // TODO: check the field is the correct sort?
128 // or let users hang themselves at this stage and check later?
129 $views[$view->id()] = $view->id();
133 $form['subquery_view'] = [
135 '#title' => $this->t('Representative view'),
136 '#default_value' => $this->options['subquery_view'],
137 '#options' => $views,
138 '#description' => $this->t('Advanced. Use another view to generate the relationship subquery. This allows you to use filtering and more than one sort. If you pick a view here, the sort options above are ignored. Your view must have the ID of its base as its only field, and should have some kind of sorting.'),
141 $form['subquery_regenerate'] = [
142 '#type' => 'checkbox',
143 '#title' => $this->t('Generate subquery each time view is run'),
144 '#default_value' => $this->options['subquery_regenerate'],
145 '#description' => $this->t('Will re-generate the subquery for this relationship every time the view is run, instead of only when these options are saved. Use for testing if you are making changes elsewhere. WARNING: seriously impairs performance.'),
150 * Helper function to create a pseudo view.
152 * We use this to obtain our subquery SQL.
154 protected function getTemporaryView() {
155 $view = View::create(['base_table' => $this->definition['base']]);
156 $view->addDisplay('default');
157 return $view->getExecutable();
161 * When the form is submitted, make sure to clear the subquery string cache.
163 public function submitOptionsForm(&$form, FormStateInterface $form_state) {
164 $cid = 'views_relationship_groupwise_max:' . $this->view->storage->id() . ':' . $this->view->current_display . ':' . $this->options['id'];
165 \Drupal::cache('data')->delete($cid);
169 * Generate a subquery given the user options, as set in the options.
171 * These are passed in rather than picked up from the object because we
172 * generate the subquery when the options are saved, rather than when the view
173 * is run. This saves considerable time.
176 * An array of options:
177 * - subquery_sort: the id of a views sort.
178 * - subquery_order: either ASC or DESC.
181 * The subquery SQL string, ready for use in the main query.
183 protected function leftQuery($options) {
184 // Either load another view, or create one on the fly.
185 if ($options['subquery_view']) {
186 $temp_view = Views::getView($options['subquery_view']);
187 // Remove all fields from default display
188 unset($temp_view->display['default']['display_options']['fields']);
191 // Create a new view object on the fly, which we use to generate a query
192 // object and then get the SQL we need for the subquery.
193 $temp_view = $this->getTemporaryView();
195 // Add the sort from the options to the default display.
196 // This is broken, in that the sort order field also gets added as a
197 // select field. See https://www.drupal.org/node/844910.
198 // We work around this further down.
199 $sort = $options['subquery_sort'];
200 list($sort_table, $sort_field) = explode('.', $sort);
201 $sort_options = ['order' => $options['subquery_order']];
202 $temp_view->addHandler('default', 'sort', $sort_table, $sort_field, $sort_options);
205 // Get the namespace string.
206 $temp_view->namespace = (!empty($options['subquery_namespace'])) ? '_' . $options['subquery_namespace'] : '_INNER';
207 $this->subquery_namespace = (!empty($options['subquery_namespace'])) ? '_' . $options['subquery_namespace'] : 'INNER';
209 // The value we add here does nothing, but doing this adds the right tables
210 // and puts in a WHERE clause with a placeholder we can grab later.
211 $temp_view->args[] = '**CORRELATED**';
213 // Add the base table ID field.
214 $temp_view->addHandler('default', 'field', $this->definition['base'], $this->definition['field']);
216 $relationship_id = NULL;
217 // Add the used relationship for the subjoin, if defined.
218 if (isset($this->definition['relationship'])) {
219 list($relationship_table, $relationship_field) = explode(':', $this->definition['relationship']);
220 $relationship_id = $temp_view->addHandler('default', 'relationship', $relationship_table, $relationship_field);
222 $temp_item_options = ['relationship' => $relationship_id];
224 // Add the correct argument for our relationship's base
225 // ie the 'how to get back to base' argument.
226 // The relationship definition tells us which one to use.
227 $temp_view->addHandler('default', 'argument', $this->definition['argument table'], $this->definition['argument field'], $temp_item_options);
229 // Build the view. The creates the query object and produces the query
230 // string but does not run any queries.
233 // Now take the SelectQuery object the View has built and massage it
234 // somewhat so we can get the SQL query from it.
235 $subquery = $temp_view->build_info['query'];
237 // Workaround until https://www.drupal.org/node/844910 is fixed:
238 // Remove all fields from the SELECT except the base id.
239 $fields = &$subquery->getFields();
240 foreach (array_keys($fields) as $field_name) {
241 // The base id for this subquery is stored in our definition.
242 if ($field_name != $this->definition['field']) {
243 unset($fields[$field_name]);
247 // Make every alias in the subquery safe within the outer query by
248 // appending a namespace to it, '_inner' by default.
249 $tables = &$subquery->getTables();
250 foreach (array_keys($tables) as $table_name) {
251 $tables[$table_name]['alias'] .= $this->subquery_namespace;
252 // Namespace the join on every table.
253 if (isset($tables[$table_name]['condition'])) {
254 $tables[$table_name]['condition'] = $this->conditionNamespace($tables[$table_name]['condition']);
258 foreach (array_keys($fields) as $field_name) {
259 $fields[$field_name]['table'] .= $this->subquery_namespace;
260 $fields[$field_name]['alias'] .= $this->subquery_namespace;
262 // Namespace conditions.
263 $where = &$subquery->conditions();
264 $this->alterSubqueryCondition($subquery, $where);
265 // Not sure why, but our sort order clause doesn't have a table.
266 // TODO: the call to addHandler() above to add the sort handler is probably
267 // wrong -- needs attention from someone who understands it.
268 // In the meantime, this works, but with a leap of faith.
269 $orders = &$subquery->getOrderBy();
270 foreach ($orders as $order_key => $order) {
271 // But if we're using a whole view, we don't know what we have!
272 if ($options['subquery_view']) {
273 list($sort_table, $sort_field) = explode('.', $order_key);
275 $orders[$sort_table . $this->subquery_namespace . '.' . $sort_field] = $order;
276 unset($orders[$order_key]);
279 // The query we get doesn't include the LIMIT, so add it here.
280 $subquery->range(0, 1);
282 // Extract the SQL the temporary view built.
283 $subquery_sql = $subquery->__toString();
285 // Replace the placeholder with the outer, correlated field.
286 // Eg, change the placeholder ':users_uid' into the outer field 'users.uid'.
287 // We have to work directly with the SQL, because putting a name of a field
288 // into a SelectQuery that it does not recognize (because it's outer) just
289 // makes it treat it as a string.
290 $outer_placeholder = ':' . str_replace('.', '_', $this->definition['outer field']);
291 $subquery_sql = str_replace($outer_placeholder, $this->definition['outer field'], $subquery_sql);
293 return $subquery_sql;
297 * Recursive helper to add a namespace to conditions.
299 * Similar to _views_query_tag_alter_condition().
301 * (Though why is the condition we get in a simple query 3 levels deep???)
303 protected function alterSubqueryCondition(AlterableInterface $query, &$conditions) {
304 foreach ($conditions as $condition_id => &$condition) {
305 // Skip the #conjunction element.
306 if (is_numeric($condition_id)) {
307 if (is_string($condition['field'])) {
308 $condition['field'] = $this->conditionNamespace($condition['field']);
310 elseif (is_object($condition['field'])) {
311 $sub_conditions = &$condition['field']->conditions();
312 $this->alterSubqueryCondition($query, $sub_conditions);
319 * Helper function to namespace query pieces.
321 * Turns 'foo.bar' into '"foo_NAMESPACE".bar'.
322 * PostgreSQL doesn't support mixed-cased identifiers unless quoted, so we
323 * need to quote each single part to prevent from query exceptions.
325 protected function conditionNamespace($string) {
326 $parts = explode(' = ', $string);
327 foreach ($parts as &$part) {
328 if (strpos($part, '.') !== FALSE) {
329 $part = '"' . str_replace('.', $this->subquery_namespace . '".', $part);
333 return implode(' = ', $parts);
339 public function query() {
340 // Figure out what base table this relationship brings to the party.
341 $table_data = Views::viewsData()->get($this->definition['base']);
342 $base_field = empty($this->definition['base field']) ? $table_data['table']['base']['field'] : $this->definition['base field'];
344 $this->ensureMyTable();
346 $def = $this->definition;
347 $def['table'] = $this->definition['base'];
348 $def['field'] = $base_field;
349 $def['left_table'] = $this->tableAlias;
350 $def['left_field'] = $this->field;
351 $def['adjusted'] = TRUE;
352 if (!empty($this->options['required'])) {
353 $def['type'] = 'INNER';
356 if ($this->options['subquery_regenerate']) {
357 // For testing only, regenerate the subquery each time.
358 $def['left_query'] = $this->leftQuery($this->options);
361 // Get the stored subquery SQL string.
362 $cid = 'views_relationship_groupwise_max:' . $this->view->storage->id() . ':' . $this->view->current_display . ':' . $this->options['id'];
363 $cache = \Drupal::cache('data')->get($cid);
364 if (isset($cache->data)) {
365 $def['left_query'] = $cache->data;
368 $def['left_query'] = $this->leftQuery($this->options);
369 \Drupal::cache('data')->set($cid, $def['left_query']);
373 if (!empty($def['join_id'])) {
374 $id = $def['join_id'];
379 $join = Views::pluginManager('join')->createInstance($id, $def);
381 // use a short alias for this:
382 $alias = $def['table'] . '_' . $this->table;
384 $this->alias = $this->query->addRelationship($alias, $join, $this->definition['base'], $this->relationship);