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'],
118 // WIP: This stuff doesn't work yet: namespacing issues.
119 // A list of suitable views to pick one as the subview.
120 $views = ['' => '- None -'];
121 foreach (Views::getAllViews() as $view) {
122 // Only get views that are suitable:
123 // - base must the base that our relationship joins towards
124 // - must have fields.
125 if ($view->get('base_table') == $this->definition['base'] && !empty($view->getDisplay('default')['display_options']['fields'])) {
126 // TODO: check the field is the correct sort?
127 // or let users hang themselves at this stage and check later?
128 $views[$view->id()] = $view->id();
132 $form['subquery_view'] = [
134 '#title' => $this->t('Representative view'),
135 '#default_value' => $this->options['subquery_view'],
136 '#options' => $views,
137 '#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.'),
140 $form['subquery_regenerate'] = [
141 '#type' => 'checkbox',
142 '#title' => $this->t('Generate subquery each time view is run'),
143 '#default_value' => $this->options['subquery_regenerate'],
144 '#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.'),
149 * Helper function to create a pseudo view.
151 * We use this to obtain our subquery SQL.
153 protected function getTemporaryView() {
154 $view = View::create(['base_table' => $this->definition['base']]);
155 $view->addDisplay('default');
156 return $view->getExecutable();
160 * When the form is submitted, make sure to clear the subquery string cache.
162 public function submitOptionsForm(&$form, FormStateInterface $form_state) {
163 $cid = 'views_relationship_groupwise_max:' . $this->view->storage->id() . ':' . $this->view->current_display . ':' . $this->options['id'];
164 \Drupal::cache('data')->delete($cid);
168 * Generate a subquery given the user options, as set in the options.
170 * These are passed in rather than picked up from the object because we
171 * generate the subquery when the options are saved, rather than when the view
172 * is run. This saves considerable time.
175 * An array of options:
176 * - subquery_sort: the id of a views sort.
177 * - subquery_order: either ASC or DESC.
180 * The subquery SQL string, ready for use in the main query.
182 protected function leftQuery($options) {
183 // Either load another view, or create one on the fly.
184 if ($options['subquery_view']) {
185 $temp_view = Views::getView($options['subquery_view']);
186 // Remove all fields from default display
187 unset($temp_view->display['default']['display_options']['fields']);
190 // Create a new view object on the fly, which we use to generate a query
191 // object and then get the SQL we need for the subquery.
192 $temp_view = $this->getTemporaryView();
194 // Add the sort from the options to the default display.
195 // This is broken, in that the sort order field also gets added as a
196 // select field. See https://www.drupal.org/node/844910.
197 // We work around this further down.
198 $sort = $options['subquery_sort'];
199 list($sort_table, $sort_field) = explode('.', $sort);
200 $sort_options = ['order' => $options['subquery_order']];
201 $temp_view->addHandler('default', 'sort', $sort_table, $sort_field, $sort_options);
204 // Get the namespace string.
205 $temp_view->namespace = (!empty($options['subquery_namespace'])) ? '_' . $options['subquery_namespace'] : '_INNER';
206 $this->subquery_namespace = (!empty($options['subquery_namespace'])) ? '_' . $options['subquery_namespace'] : 'INNER';
208 // The value we add here does nothing, but doing this adds the right tables
209 // and puts in a WHERE clause with a placeholder we can grab later.
210 $temp_view->args[] = '**CORRELATED**';
212 // Add the base table ID field.
213 $temp_view->addHandler('default', 'field', $this->definition['base'], $this->definition['field']);
215 $relationship_id = NULL;
216 // Add the used relationship for the subjoin, if defined.
217 if (isset($this->definition['relationship'])) {
218 list($relationship_table, $relationship_field) = explode(':', $this->definition['relationship']);
219 $relationship_id = $temp_view->addHandler('default', 'relationship', $relationship_table, $relationship_field);
221 $temp_item_options = ['relationship' => $relationship_id];
223 // Add the correct argument for our relationship's base
224 // ie the 'how to get back to base' argument.
225 // The relationship definition tells us which one to use.
226 $temp_view->addHandler('default', 'argument', $this->definition['argument table'], $this->definition['argument field'], $temp_item_options);
228 // Build the view. The creates the query object and produces the query
229 // string but does not run any queries.
232 // Now take the SelectQuery object the View has built and massage it
233 // somewhat so we can get the SQL query from it.
234 $subquery = $temp_view->build_info['query'];
236 // Workaround until https://www.drupal.org/node/844910 is fixed:
237 // Remove all fields from the SELECT except the base id.
238 $fields = &$subquery->getFields();
239 foreach (array_keys($fields) as $field_name) {
240 // The base id for this subquery is stored in our definition.
241 if ($field_name != $this->definition['field']) {
242 unset($fields[$field_name]);
246 // Make every alias in the subquery safe within the outer query by
247 // appending a namespace to it, '_inner' by default.
248 $tables = &$subquery->getTables();
249 foreach (array_keys($tables) as $table_name) {
250 $tables[$table_name]['alias'] .= $this->subquery_namespace;
251 // Namespace the join on every table.
252 if (isset($tables[$table_name]['condition'])) {
253 $tables[$table_name]['condition'] = $this->conditionNamespace($tables[$table_name]['condition']);
257 foreach (array_keys($fields) as $field_name) {
258 $fields[$field_name]['table'] .= $this->subquery_namespace;
259 $fields[$field_name]['alias'] .= $this->subquery_namespace;
261 // Namespace conditions.
262 $where = &$subquery->conditions();
263 $this->alterSubqueryCondition($subquery, $where);
264 // Not sure why, but our sort order clause doesn't have a table.
265 // TODO: the call to addHandler() above to add the sort handler is probably
266 // wrong -- needs attention from someone who understands it.
267 // In the meantime, this works, but with a leap of faith.
268 $orders = &$subquery->getOrderBy();
269 foreach ($orders as $order_key => $order) {
270 // But if we're using a whole view, we don't know what we have!
271 if ($options['subquery_view']) {
272 list($sort_table, $sort_field) = explode('.', $order_key);
274 $orders[$sort_table . $this->subquery_namespace . '.' . $sort_field] = $order;
275 unset($orders[$order_key]);
278 // The query we get doesn't include the LIMIT, so add it here.
279 $subquery->range(0, 1);
281 // Extract the SQL the temporary view built.
282 $subquery_sql = $subquery->__toString();
284 // Replace the placeholder with the outer, correlated field.
285 // Eg, change the placeholder ':users_uid' into the outer field 'users.uid'.
286 // We have to work directly with the SQL, because putting a name of a field
287 // into a SelectQuery that it does not recognize (because it's outer) just
288 // makes it treat it as a string.
289 $outer_placeholder = ':' . str_replace('.', '_', $this->definition['outer field']);
290 $subquery_sql = str_replace($outer_placeholder, $this->definition['outer field'], $subquery_sql);
292 return $subquery_sql;
296 * Recursive helper to add a namespace to conditions.
298 * Similar to _views_query_tag_alter_condition().
300 * (Though why is the condition we get in a simple query 3 levels deep???)
302 protected function alterSubqueryCondition(AlterableInterface $query, &$conditions) {
303 foreach ($conditions as $condition_id => &$condition) {
304 // Skip the #conjunction element.
305 if (is_numeric($condition_id)) {
306 if (is_string($condition['field'])) {
307 $condition['field'] = $this->conditionNamespace($condition['field']);
309 elseif (is_object($condition['field'])) {
310 $sub_conditions = &$condition['field']->conditions();
311 $this->alterSubqueryCondition($query, $sub_conditions);
318 * Helper function to namespace query pieces.
320 * Turns 'foo.bar' into '"foo_NAMESPACE".bar'.
321 * PostgreSQL doesn't support mixed-cased identifiers unless quoted, so we
322 * need to quote each single part to prevent from query exceptions.
324 protected function conditionNamespace($string) {
325 $parts = explode(' = ', $string);
326 foreach ($parts as &$part) {
327 if (strpos($part, '.') !== FALSE) {
328 $part = '"' . str_replace('.', $this->subquery_namespace . '".', $part);
332 return implode(' = ', $parts);
338 public function query() {
339 // Figure out what base table this relationship brings to the party.
340 $table_data = Views::viewsData()->get($this->definition['base']);
341 $base_field = empty($this->definition['base field']) ? $table_data['table']['base']['field'] : $this->definition['base field'];
343 $this->ensureMyTable();
345 $def = $this->definition;
346 $def['table'] = $this->definition['base'];
347 $def['field'] = $base_field;
348 $def['left_table'] = $this->tableAlias;
349 $def['left_field'] = $this->field;
350 $def['adjusted'] = TRUE;
351 if (!empty($this->options['required'])) {
352 $def['type'] = 'INNER';
355 if ($this->options['subquery_regenerate']) {
356 // For testing only, regenerate the subquery each time.
357 $def['left_query'] = $this->leftQuery($this->options);
360 // Get the stored subquery SQL string.
361 $cid = 'views_relationship_groupwise_max:' . $this->view->storage->id() . ':' . $this->view->current_display . ':' . $this->options['id'];
362 $cache = \Drupal::cache('data')->get($cid);
363 if (isset($cache->data)) {
364 $def['left_query'] = $cache->data;
367 $def['left_query'] = $this->leftQuery($this->options);
368 \Drupal::cache('data')->set($cid, $def['left_query']);
372 if (!empty($def['join_id'])) {
373 $id = $def['join_id'];
378 $join = Views::pluginManager('join')->createInstance($id, $def);
380 // use a short alias for this:
381 $alias = $def['table'] . '_' . $this->table;
383 $this->alias = $this->query->addRelationship($alias, $join, $this->definition['base'], $this->relationship);