class Sql extends QueryPluginBase (View source)

Views query plugin for an SQL query.

Traits

Wrapper methods for \Drupal\Core\StringTranslation\TranslationInterface.

Provides dependency injection friendly methods for serialization.

Provides a trait for the messenger service.

Constants

DERIVATIVE_SEPARATOR

A string which is used to separate base plugin IDs from the derivative ID.

INCLUDE_NEGOTIATED

Include negotiated languages when listing languages.

INCLUDE_ENTITY

Include entity row languages when listing languages.

VIEWS_QUERY_LANGUAGE_SITE_DEFAULT

Query string to indicate the site default language.

Properties

protected string $pluginId

The plugin_id.

from  PluginBase
protected array $pluginDefinition

The plugin implementation definition.

from  PluginBase
protected array $configuration

Configuration information passed into the plugin.

from  PluginBase
protected TranslationInterface $stringTranslation

The string translation service.

from  StringTranslationTrait
protected array $_serviceIds

An array of service IDs keyed by property name used for serialization.

from  DependencySerializationTrait
protected array $_entityStorages

An array of entity type IDs keyed by the property name of their storages.

from  DependencySerializationTrait
protected MessengerInterface $messenger

The messenger.

array $options

Options for this plugin will be held here.

from  PluginBase
ViewExecutable $view

The top object of a view.

from  PluginBase
DisplayPluginBase $displayHandler

The display object this plugin is for.

from  PluginBase
array $definition

Plugins's definition.

from  PluginBase
protected bool $usesOptions

Denotes whether the plugin has an additional options form.

from  PluginBase
protected RendererInterface $renderer

Stores the render API renderer.

from  PluginBase
views_plugin_pager $pager

A pager plugin that should be provided by the display.

from  QueryPluginBase
protected int $limit

Stores the limit of items that should be requested in the query.

from  QueryPluginBase
protected $tableQueue

A list of tables in the order they should be added, keyed by alias.

$tables

Holds an array of tables and counts added so that we can create aliases.

$relationships

Holds an array of relationships, which are aliases of the primary table that represent different ways to join the same table in.

$where

An array of sections of the WHERE query. Each section is in itself an array of pieces and a flag as to whether or not it should be AND or OR.

$having

An array of sections of the HAVING query. Each section is in itself an array of pieces and a flag as to whether or not it should be AND or OR.

protected string $groupOperator

The default operator to use when connecting the WHERE groups. May be AND or OR.

$orderby

A simple array of order by clauses.

$groupby

A simple array of group by clauses.

$fields

An array of fields.

bool $distinct

A flag as to whether or not to make the primary field distinct.

protected bool $hasAggregate
protected $getCountOptimized

Should this query be optimized for counts, for example no sorts.

protected $fieldAliases

An array mapping table aliases and field names to field aliases.

$tags

Query tags which will be passed over to the dbtng query object.

protected bool $noDistinct

Is the view marked as not distinct.

protected EntityTypeManagerInterface $entityTypeManager

The entity type manager.

protected DateSqlInterface $dateSql

The database-specific date handler.

Methods

__construct(array $configuration, string $plugin_id, mixed $plugin_definition, EntityTypeManagerInterface $entity_type_manager, DateSqlInterface $date_sql, MessengerInterface $messenger)

Constructs a Sql object.

string
getPluginId()

Gets the plugin_id of the plugin instance.

string
getBaseId()

Gets the base_plugin_id of the plugin instance.

string|null
getDerivativeId()

Gets the derivative_id of the plugin instance.

array
getPluginDefinition()

Gets the definition of the plugin implementation.

bool
isConfigurable()

Determines if the plugin is configurable.

t(string $string, array $args = [], array $options = [])

Translates a string to the current language or to a given language.

formatPlural($count, $singular, $plural, array $args = [], array $options = [])

Formats a string containing a count of items.

getNumberOfPlurals($langcode = NULL)

Returns the number of plurals supported by a given language.

getStringTranslation()

Gets the string translation service.

$this
setStringTranslation(TranslationInterface $translation)

Sets the string translation service to use.

__sleep()

{@inheritdoc}

__wakeup()

{@inheritdoc}

setMessenger(MessengerInterface $messenger)

Sets the messenger.

messenger()

Gets the messenger.

create(ContainerInterface $container, array $configuration, string $plugin_id, mixed $plugin_definition)

Creates an instance of the plugin.

init(ViewExecutable $view, DisplayPluginBase $display, array $options = NULL)

Initialize the plugin.

array
defineOptions()

Information about options for all kinds of purposes will be held here.

setOptionDefaults(array $storage, array $options)

Fills up the options of the plugin with defaults.

filterByDefinedOptions(array $storage)

Filter out stored options depending on the defined options.

doFilterByDefinedOptions(array $storage, array $options)

Do the work to filter out stored options depending on the defined options.

unpackOptions($storage, $options, $definition = NULL, $all = TRUE, $check = TRUE)

Unpack options over our existing defaults, drilling down into arrays so that defaults don't get totally blown away.

destroy()

Clears a plugin.

buildOptionsForm($form, FormStateInterface $form_state)

Add settings for the ui.

static string[]
trustedCallbacks()

Lists the trusted callbacks provided by the implementing class.

validateOptionsForm($form, FormStateInterface $form_state)

Validate the options form.

submitOptionsForm($form, FormStateInterface $form_state)

Special submit handling.

query($get_count = FALSE)

Generate a query and a countquery from all of the information supplied to the object.

themeFunctions()

Provide a full list of possible theme templates used by this style.

An
validate()

Validate that the plugin is correct and can be saved.

summaryTitle()

Returns the summary of the settings in the display.

pluginTitle()

Return the human readable name of the display.

usesOptions()

Returns the usesOptions property.

string
globalTokenReplace(string $string = '', array $options = [])

Returns a string with any core tokens replaced.

string
viewsTokenReplace($text, $tokens)

Replaces Views' tokens in a given string. The resulting string will be sanitized with Xss::filterAdmin.

array
getAvailableGlobalTokens(bool $prepared = FALSE, array $types = [])

Returns an array of available token replacements.

globalTokenForm(array $form, FormStateInterface $form_state)

Adds elements for available core tokens to a form.

static array
preRenderAddFieldsetMarkup(array $form)

Moves form elements into fieldsets for presentation purposes.

static array
preRenderFlattenData(array $form)

Flattens the structure of form elements.

array
calculateDependencies()

Calculates dependencies for the configured plugin.

string
getProvider()

Returns the plugin provider.

array
listLanguages(int $flags = LanguageInterface::STATE_ALL, array $current_values = NULL)

Makes an array of languages, optionally including special languages.

static array
queryLanguageSubstitutions()

Returns substitutions for Views queries for languages.

getRenderer()

Returns the render API renderer.

alter(ViewExecutable $view)

Let modules modify the query just prior to finalizing it.

build(ViewExecutable $view)

Builds the necessary info to execute the query.

execute(ViewExecutable $view)

Executes the query and fills the associated view object with according values.

addSignature(ViewExecutable $view)

Add a signature to the query, if such a thing is feasible.

getAggregationInfo()

Get aggregation info for group by queries.

setLimit($limit)

Set a LIMIT on the query, specifying a maximum number of results.

setOffset($offset)

Set an OFFSET on the query, specifying a number of results to skip.

getLimit()

Returns the limit of the query.

The
setWhereGroup($type = 'AND', $group = NULL, $where = 'where')

Create a new grouping for the WHERE or HAVING clause.

setGroupOperator($type = 'AND')

Control how all WHERE and HAVING groups are put together.

loadEntities($results)

Loads all entities contained in the passed-in $results.

string
getDateField(string $field, bool $string_date = FALSE, bool $calculate_offset = TRUE)

Returns a Unix timestamp to database native timestamp expression.

string
setupTimezone()

Set the database to the current user timezone.

string
getDateFormat(string $field, string $format, bool $string_date = FALSE)

Creates cross-database date formatting.

array
getEntityTableInfo()

Returns an array of all tables from the query that map to an entity type.

int
getCacheMaxAge()

The maximum age for which this object may be cached.

string[]
getCacheContexts()

The cache contexts associated with this object.

string[]
getCacheTags()

The cache tags associated with this object.

setFieldTimezoneOffset(string $field, int $offset)

Applies a timezone offset to the given field.

int
getTimezoneOffset()

Get the timezone offset in seconds.

array
getTableQueue()

Returns a reference to the table queue array for this query.

setDistinct(bool $value = TRUE)

Set the view to be distinct (per base field).

setCountField($table, $field, $alias = NULL)

Set what field the query will count() on for paging.

addRelationship($alias, JoinPluginBase $join, $base, $link_point = NULL)

A relationship is an alternative endpoint to a series of table joins. Relationships must be aliases of the primary table and they must join either to the primary table or to a pre-existing relationship.

string
addTable($table, $relationship = NULL, JoinPluginBase $join = NULL, $alias = NULL)

Add a table to the query, ensuring the path exists.

string
queueTable($table, $relationship = NULL, JoinPluginBase $join = NULL, $alias = NULL)

Add a table to the query without ensuring the path.

markTable($table, $relationship, $alias)

No description

The
ensureTable($table, $relationship = NULL, JoinPluginBase $join = NULL)

Ensure a table exists in the queue; if it already exists it won't do anything, but if it doesn't it will add the table queue. It will ensure a path leads back to the relationship table.

ensurePath($table, $relationship = NULL, $join = NULL, $traced = [], $add = [])

Make sure that the specified table can be properly linked to the primary table in the JOINs. This function uses recursion. If the tables needed to complete the path back to the primary table are not in the query they will be added, but additional copies will NOT be added if the table is already there.

adjustJoin($join, $relationship)

Fix a join to adhere to the proper relationship; the left table can vary based upon what relationship items are joined in on.

getJoinData($table, $base_table)

Retrieve join data from the larger join data cache.

getTableInfo($table)

Get the information associated with a table.

string
addField($table, $field, $alias = '', $params = [])

Add a field to the query table, possibly with an alias. This will automatically call ensureTable to make sure the required table exists, unless $table is unset.

clearFields()

Remove all fields that may have been added; primarily used for summary mode where we're changing the query because we didn't get data we needed.

addWhere($group, $field, $value = NULL, $operator = NULL)

Add a simple WHERE clause to the query. The caller is responsible for ensuring that all fields are fully qualified (TABLE.FIELD) and that the table already exists in the query.

addWhereExpression($group, $snippet, $args = [])

Add a complex WHERE clause to the query.

addHavingExpression($group, $snippet, $args = [])

Add a complex HAVING clause to the query.

addOrderBy($table, $field = NULL, $order = 'ASC', $alias = '', $params = [])

Add an ORDER BY clause to the query.

addGroupBy($clause)

Add a simple GROUP BY clause to the query. The caller is responsible for ensuring that the fields are fully qualified and the table is properly added.

getFieldAlias($table_alias, $field)

Returns the alias for the given field added to $table.

addTag($tag)

Adds a query tag to the sql object.

placeholder($base = 'views')

Generates a unique placeholder used in the db query.

buildCondition($where = 'where')

Construct the "WHERE" or "HAVING" part of the query.

array
getNonAggregates()

Returns a list of non-aggregates to be added to the "group by" clause.

compileFields(SelectInterface $query)

Adds fields to the query.

getConnection()

Gets the database connection to use for the view.

getWhereArgs()

Get the arguments attached to the WHERE and HAVING clauses of this query.

assignEntitiesToResult(array[] $ids, array $entities, array $results)

Sets entities onto the view result row objects.

getAllEntities()

Gets all the involved entities of the view.

aggregationMethodSimple($group_type, $field)

No description

aggregationMethodDistinct($group_type, $field)

No description

Details

__construct(array $configuration, string $plugin_id, mixed $plugin_definition, EntityTypeManagerInterface $entity_type_manager, DateSqlInterface $date_sql, MessengerInterface $messenger)

Constructs a Sql object.

Parameters

array $configuration

A configuration array containing information about the plugin instance.

string $plugin_id

The plugin_id for the plugin instance.

mixed $plugin_definition

The plugin implementation definition.

EntityTypeManagerInterface $entity_type_manager

The entity type manager.

DateSqlInterface $date_sql

The database-specific date handler.

MessengerInterface $messenger

The messenger.

string getPluginId()

Gets the plugin_id of the plugin instance.

Return Value

string

The plugin_id of the plugin instance.

string getBaseId()

Gets the base_plugin_id of the plugin instance.

Return Value

string

The base_plugin_id of the plugin instance.

string|null getDerivativeId()

Gets the derivative_id of the plugin instance.

Return Value

string|null

The derivative_id of the plugin instance NULL otherwise.

array getPluginDefinition()

Gets the definition of the plugin implementation.

Return Value

array

The plugin definition, as returned by the discovery object used by the plugin manager.

bool isConfigurable()

Determines if the plugin is configurable.

Return Value

bool

A boolean indicating whether the plugin is configurable.

protected TranslatableMarkup t(string $string, array $args = [], array $options = [])

Translates a string to the current language or to a given language.

See \Drupal\Core\StringTranslation\TranslatableMarkup::__construct() for important security information and usage guidelines.

In order for strings to be localized, make them available in one of the ways supported by the

Parameters

string $string

A string containing the English text to translate.

array $args

(optional) An associative array of replacements to make after translation. Based on the first character of the key, the value is escaped and/or themed. See \Drupal\Component\Render\FormattableMarkup::placeholderFormat() for details.

array $options

(optional) An associative array of additional options, with the following elements:

  • 'langcode' (defaults to the current language): A language code, to translate to a language other than what is used to display the page.
  • 'context' (defaults to the empty context): The context the source string belongs to. See the @link i18n Internationalization topic @endlink for more information about string contexts.

Return Value

TranslatableMarkup

An object that, when cast to a string, returns the translated string.

See also

FormattableMarkup::placeholderFormat
TranslatableMarkup::__construct

protected formatPlural($count, $singular, $plural, array $args = [], array $options = [])

Formats a string containing a count of items.

Parameters

$count
$singular
$plural
array $args
array $options

See also

TranslationInterface::formatPlural

protected getNumberOfPlurals($langcode = NULL)

Returns the number of plurals supported by a given language.

Parameters

$langcode

See also

PluralFormulaInterface::getNumberOfPlurals

protected TranslationInterface getStringTranslation()

Gets the string translation service.

Return Value

TranslationInterface

The string translation service.

$this setStringTranslation(TranslationInterface $translation)

Sets the string translation service to use.

Parameters

TranslationInterface $translation

The string translation service.

Return Value

$this

__sleep()

{@inheritdoc}

__wakeup()

{@inheritdoc}

setMessenger(MessengerInterface $messenger)

Sets the messenger.

Parameters

MessengerInterface $messenger

The messenger.

MessengerInterface messenger()

Gets the messenger.

Return Value

MessengerInterface

The messenger.

static ContainerFactoryPluginInterface create(ContainerInterface $container, array $configuration, string $plugin_id, mixed $plugin_definition)

Creates an instance of the plugin.

Parameters

ContainerInterface $container

The container to pull out services used in the plugin.

array $configuration

A configuration array containing information about the plugin instance.

string $plugin_id

The plugin ID for the plugin instance.

mixed $plugin_definition

The plugin implementation definition.

Return Value

ContainerFactoryPluginInterface

Returns an instance of this plugin.

init(ViewExecutable $view, DisplayPluginBase $display, array $options = NULL)

Initialize the plugin.

Parameters

ViewExecutable $view

The view object.

DisplayPluginBase $display

The display handler.

array $options

The options configured for this plugin.

protected array defineOptions()

Information about options for all kinds of purposes will be held here.

Return Value

array

Returns the options of this handler/plugin.

protected setOptionDefaults(array $storage, array $options)

Fills up the options of the plugin with defaults.

Parameters

array $storage

An array which stores the actual option values of the plugin.

array $options

An array which describes the options of a plugin. Each element is an associative array containing:

  • default: The default value of one option. Should be translated to the interface text language selected for page if translatable.
  • (optional) contains: An array which describes the available options under the key. If contains is set, the default will be ignored and assumed to be an empty array.
  • (optional) 'bool': TRUE if the value is boolean, else FALSE.

filterByDefinedOptions(array $storage)

Filter out stored options depending on the defined options.

Parameters

array $storage

The stored options.

protected doFilterByDefinedOptions(array $storage, array $options)

Do the work to filter out stored options depending on the defined options.

Parameters

array $storage

The stored options.

array $options

The defined options.

unpackOptions($storage, $options, $definition = NULL, $all = TRUE, $check = TRUE)

Unpack options over our existing defaults, drilling down into arrays so that defaults don't get totally blown away.

Parameters

$storage
$options
$definition
$all
$check

destroy()

Clears a plugin.

buildOptionsForm($form, FormStateInterface $form_state)

Add settings for the ui.

Parameters

$form
FormStateInterface $form_state

static string[] trustedCallbacks()

Lists the trusted callbacks provided by the implementing class.

Trusted callbacks are public methods on the implementing class and can be invoked via \Drupal\Core\Security\DoTrustedCallbackTrait::doTrustedCallback().

Return Value

string[]

List of method names implemented by the class that can be used as trusted callbacks.

validateOptionsForm($form, FormStateInterface $form_state)

Validate the options form.

Parameters

$form
FormStateInterface $form_state

submitOptionsForm($form, FormStateInterface $form_state)

Special submit handling.

Parameters

$form
FormStateInterface $form_state

query($get_count = FALSE)

Generate a query and a countquery from all of the information supplied to the object.

Parameters

$get_count

Provide a countquery if this is true, otherwise provide a normal query.

themeFunctions()

Provide a full list of possible theme templates used by this style.

An validate()

Validate that the plugin is correct and can be saved.

Return Value

An

array of error strings to tell the user what is wrong with this plugin.

summaryTitle()

Returns the summary of the settings in the display.

pluginTitle()

Return the human readable name of the display.

This appears on the ui beside each plugin and beside the settings link.

usesOptions()

Returns the usesOptions property.

string globalTokenReplace(string $string = '', array $options = [])

Returns a string with any core tokens replaced.

Parameters

string $string

The string to preform the token replacement on.

array $options

An array of options, as passed to \Drupal\Core\Utility\Token::replace().

Return Value

string

The tokenized string.

protected string viewsTokenReplace($text, $tokens)

Replaces Views' tokens in a given string. The resulting string will be sanitized with Xss::filterAdmin.

Parameters

$text

Unsanitized string with possible tokens.

$tokens

Array of token => replacement_value items.

Return Value

string

array getAvailableGlobalTokens(bool $prepared = FALSE, array $types = [])

Returns an array of available token replacements.

Parameters

bool $prepared

Whether to return the raw token info for each token or an array of prepared tokens for each type. E.g. "[view:name]".

array $types

An array of additional token types to return, defaults to 'site' and 'view'.

Return Value

array

An array of available token replacement info or tokens, grouped by type.

globalTokenForm(array $form, FormStateInterface $form_state)

Adds elements for available core tokens to a form.

Parameters

array $form

The form array to alter, passed by reference.

FormStateInterface $form_state

The current state of the form.

static array preRenderAddFieldsetMarkup(array $form)

Moves form elements into fieldsets for presentation purposes.

Many views forms use #tree = TRUE to keep their values in a hierarchy for easier storage. Moving the form elements into fieldsets during form building would break up that hierarchy. Therefore, we wait until the pre_render stage, where any changes we make affect presentation only and aren't reflected in $form_state->getValues().

Parameters

array $form

The form build array to alter.

Return Value

array

The form build array.

static array preRenderFlattenData(array $form)

Flattens the structure of form elements.

If a form element has #flatten = TRUE, then all of its children get moved to the same level as the element itself. So $form['to_be_flattened'][$key] becomes $form[$key], and $form['to_be_flattened'] gets unset.

Parameters

array $form

The form build array to alter.

Return Value

array

The form build array.

array calculateDependencies()

Calculates dependencies for the configured plugin.

Dependencies are saved in the plugin's configuration entity and are used to determine configuration synchronization order. For example, if the plugin integrates with specific user roles, this method should return an array of dependencies listing the specified roles.

Return Value

array

An array of dependencies grouped by type (config, content, module, theme). For example: @code array( 'config' => array('user.role.anonymous', 'user.role.authenticated'), 'content' => array('node:article:f0a189e6-55fb-47fb-8005-5bef81c44d6d'), 'module' => array('node', 'user'), 'theme' => array('seven'), ); @endcode

string getProvider()

Returns the plugin provider.

Return Value

string

protected array listLanguages(int $flags = LanguageInterface::STATE_ALL, array $current_values = NULL)

Makes an array of languages, optionally including special languages.

Parameters

int $flags

(optional) Flags for which languages to return (additive). Options:

  • \Drupal\Core\Language::STATE_ALL (default): All languages (configurable and default).
  • \Drupal\Core\Language::STATE_CONFIGURABLE: Configurable languages.
  • \Drupal\Core\Language::STATE_LOCKED: Locked languages.
  • \Drupal\Core\Language::STATE_SITE_DEFAULT: Add site default language; note that this is not included in STATE_ALL.
  • \Drupal\views\Plugin\views\PluginBase::INCLUDE_NEGOTIATED: Add negotiated language types.
  • \Drupal\views\Plugin\views\PluginBase::INCLUDE_ENTITY: Add entity row language types. Note that these are only supported for display options, not substituted in queries.
array $current_values

The currently-selected options in the list, if available.

Return Value

array

An array of language names, keyed by the language code. Negotiated and special languages have special codes that are substituted in queries by PluginBase::queryLanguageSubstitutions(). Only configurable languages and languages that are in $current_values are included in the list.

static array queryLanguageSubstitutions()

Returns substitutions for Views queries for languages.

This is needed so that the language options returned by PluginBase::listLanguages() are able to be used in queries. It is called by the Views module implementation of hook_views_query_substitutions() to get the language-related substitutions.

Return Value

array

An array in the format of hook_views_query_substitutions() that gives the query substitutions needed for the special language types.

protected RendererInterface getRenderer()

Returns the render API renderer.

Return Value

RendererInterface

alter(ViewExecutable $view)

Let modules modify the query just prior to finalizing it.

Parameters

ViewExecutable $view

The view which is executed.

build(ViewExecutable $view)

Builds the necessary info to execute the query.

Parameters

ViewExecutable $view

The view which is executed.

execute(ViewExecutable $view)

Executes the query and fills the associated view object with according values.

Values to set: $view->result, $view->total_rows, $view->execute_time, $view->current_page.

Parameters

ViewExecutable $view

The view which is executed.

addSignature(ViewExecutable $view)

Add a signature to the query, if such a thing is feasible.

This signature is something that can be used when perusing query logs to discern where particular queries might be coming from.

Parameters

ViewExecutable $view

The view which is executed.

getAggregationInfo()

Get aggregation info for group by queries.

If NULL, aggregation is not allowed.

setLimit($limit)

Set a LIMIT on the query, specifying a maximum number of results.

Parameters

$limit

setOffset($offset)

Set an OFFSET on the query, specifying a number of results to skip.

Parameters

$offset

getLimit()

Returns the limit of the query.

The setWhereGroup($type = 'AND', $group = NULL, $where = 'where')

Create a new grouping for the WHERE or HAVING clause.

Parameters

$type

Either 'AND' or 'OR'. All items within this group will be added to the WHERE clause with this logical operator.

$group

An ID to use for this group. If unspecified, an ID will be generated.

$where

'where' or 'having'.

Return Value

The

group ID generated.

setGroupOperator($type = 'AND')

Control how all WHERE and HAVING groups are put together.

Parameters

$type

Either 'AND' or 'OR'

loadEntities($results)

Loads all entities contained in the passed-in $results.

If the entity belongs to the base table, then it gets stored in $result->_entity. Otherwise, it gets stored in $result->_relationship_entities[$relationship_id];

Parameters

$results

string getDateField(string $field, bool $string_date = FALSE, bool $calculate_offset = TRUE)

Returns a Unix timestamp to database native timestamp expression.

Parameters

string $field

The query field that will be used in the expression.

bool $string_date

For certain databases, date format functions vary depending on string or numeric storage.

bool $calculate_offset

If set to TRUE, the timezone offset will be included in the returned field.

Return Value

string

An expression representing a timestamp with time zone.

string setupTimezone()

Set the database to the current user timezone.

Return Value

string

The current timezone as returned by date_default_timezone_get().

string getDateFormat(string $field, string $format, bool $string_date = FALSE)

Creates cross-database date formatting.

Parameters

string $field

An appropriate query expression pointing to the date field.

string $format

A format string for the result, like 'Y-m-d H:i:s'.

bool $string_date

For certain databases, date format functions vary depending on string or numeric storage.

Return Value

string

A string representing the field formatted as a date in the format specified by $format.

array getEntityTableInfo()

Returns an array of all tables from the query that map to an entity type.

Includes the base table and all relationships, if eligible.

Available keys for each table:

  • base: The actual base table (i.e. "user" for an author relationship).
  • relationship_id: The id of the relationship, or "none".
  • alias: The alias used for the relationship.
  • entity_type: The entity type matching the base table.
  • revision: A boolean that specifies whether the table is a base table or a revision table of the entity type.

Return Value

array

An array of table information, keyed by table alias.

int getCacheMaxAge()

The maximum age for which this object may be cached.

Return Value

int

The maximum time in seconds that this object may be cached.

string[] getCacheContexts()

The cache contexts associated with this object.

These identify a specific variation/representation of the object.

Cache contexts are tokens: placeholders that are converted to cache keys by the @cache_contexts_manager service. The replacement value depends on the request context (the current URL, language, and so on). They're converted before storing an object in cache.

Return Value

string[]

An array of cache context tokens, used to generate a cache ID.

string[] getCacheTags()

The cache tags associated with this object.

When this object is modified, these cache tags will be invalidated.

Return Value

string[]

A set of cache tags.

setFieldTimezoneOffset(string $field, int $offset)

Applies a timezone offset to the given field.

Parameters

string $field

The date field, in string format.

int $offset

The timezone offset to apply to the field.

int getTimezoneOffset()

Get the timezone offset in seconds.

Return Value

int

The offset, in seconds, for the timezone being used.

array getTableQueue()

Returns a reference to the table queue array for this query.

Because this method returns by reference, alter hooks may edit the tables array directly to make their changes. If just adding tables, however, the use of the addTable() method is preferred.

Note that if you want to manipulate the table queue array, this method must be called by reference as well:

Return Value

array

A reference to the table queue array structure.

protected setDistinct(bool $value = TRUE)

Set the view to be distinct (per base field).

Parameters

bool $value

Should the view be distinct.

setCountField($table, $field, $alias = NULL)

Set what field the query will count() on for paging.

Parameters

$table
$field
$alias

addRelationship($alias, JoinPluginBase $join, $base, $link_point = NULL)

A relationship is an alternative endpoint to a series of table joins. Relationships must be aliases of the primary table and they must join either to the primary table or to a pre-existing relationship.

An example of a relationship would be a node reference table. If you have a node reference named 'book_parent' which links to a parent node, you could set up a relationship 'node_book_parent' to 'node'. Then, anything that links to 'node' can link to 'node_book_parent' instead, thus allowing all properties of both nodes to be available in the query.

Parameters

$alias

What this relationship will be called, and is also the alias for the table.

JoinPluginBase $join

A Join object (or derived object) to join the alias in.

$base

The name of the 'base' table this relationship represents; this tells the join search which path to attempt to use when finding the path to this relationship.

$link_point

If this relationship links to something other than the primary table, specify that table here. For example, a 'track' node might have a relationship to an 'album' node, which might have a relationship to an 'artist' node.

string addTable($table, $relationship = NULL, JoinPluginBase $join = NULL, $alias = NULL)

Add a table to the query, ensuring the path exists.

This function will test to ensure that the path back to the primary table is valid and exists; if you do not wish for this testing to occur, use $query->queueTable() instead.

Parameters

$table

The name of the table to add. It needs to exist in the global table array.

$relationship

An alias of a table; if this is set, the path back to this table will be tested prior to adding the table, making sure that all intermediary tables exist and are properly aliased. If set to NULL the path to the primary table will be ensured. If the path cannot be made, the table will NOT be added.

JoinPluginBase $join

In some join configurations this table may actually join back through a different method; this is most likely to be used when tracing a hierarchy path. (node->parent->parent2->parent3). This parameter will specify how this table joins if it is not the default.

$alias

A specific alias to use, rather than the default alias.

Return Value

string

The alias of the table; this alias can be used to access information about the table and should always be used to refer to the table when adding parts to the query. Or FALSE if the table was not able to be added.

string queueTable($table, $relationship = NULL, JoinPluginBase $join = NULL, $alias = NULL)

Add a table to the query without ensuring the path.

This is a pretty internal function to Views and addTable() or ensureTable() should be used instead of this one, unless you are absolutely sure this is what you want.

Parameters

$table

The name of the table to add. It needs to exist in the global table array.

$relationship

The primary table alias this table is related to. If not set, the primary table will be used.

JoinPluginBase $join

In some join configurations this table may actually join back through a different method; this is most likely to be used when tracing a hierarchy path. (node->parent->parent2->parent3). This parameter will specify how this table joins if it is not the default.

$alias

A specific alias to use, rather than the default alias.

Return Value

string

The alias of the table; this alias can be used to access information about the table and should always be used to refer to the table when adding parts to the query. Or FALSE if the table was not able to be added.

protected markTable($table, $relationship, $alias)

No description

Parameters

$table
$relationship
$alias

The ensureTable($table, $relationship = NULL, JoinPluginBase $join = NULL)

Ensure a table exists in the queue; if it already exists it won't do anything, but if it doesn't it will add the table queue. It will ensure a path leads back to the relationship table.

Parameters

$table

The unaliased name of the table to ensure.

$relationship

The relationship to ensure the table links to. Each relationship will get a unique instance of the table being added. If not specified, will be the primary table.

JoinPluginBase $join

A Join object (or derived object) to join the alias in.

Return Value

The

alias used to refer to this specific table, or NULL if the table cannot be ensured.

protected ensurePath($table, $relationship = NULL, $join = NULL, $traced = [], $add = [])

Make sure that the specified table can be properly linked to the primary table in the JOINs. This function uses recursion. If the tables needed to complete the path back to the primary table are not in the query they will be added, but additional copies will NOT be added if the table is already there.

Parameters

$table
$relationship
$join
$traced
$add

protected adjustJoin($join, $relationship)

Fix a join to adhere to the proper relationship; the left table can vary based upon what relationship items are joined in on.

Parameters

$join
$relationship

JoinPluginBase getJoinData($table, $base_table)

Retrieve join data from the larger join data cache.

Parameters

$table

The table to get the join information for.

$base_table

The path we're following to get this join.

Return Value

JoinPluginBase

A Join object or child object, if one exists.

getTableInfo($table)

Get the information associated with a table.

If you need the alias of a table with a particular relationship, use ensureTable().

Parameters

$table

string addField($table, $field, $alias = '', $params = [])

Add a field to the query table, possibly with an alias. This will automatically call ensureTable to make sure the required table exists, unless $table is unset.

Parameters

$table

The table this field is attached to. If NULL, it is assumed this will be a formula; otherwise, ensureTable is used to make sure the table exists.

$field

The name of the field to add. This may be a real field or a formula.

$alias

The alias to create. If not specified, the alias will be $table_$field unless $table is NULL. When adding formulae, it is recommended that an alias be used.

$params

An array of parameters additional to the field that will control items such as aggregation functions and DISTINCT. Some values that are recognized:

  • function: An aggregation function to apply, such as SUM.
  • aggregate: Set to TRUE to indicate that this value should be aggregated in a GROUP BY.

Return Value

string

The name that this field can be referred to as. Usually this is the alias.

clearFields()

Remove all fields that may have been added; primarily used for summary mode where we're changing the query because we didn't get data we needed.

addWhere($group, $field, $value = NULL, $operator = NULL)

Add a simple WHERE clause to the query. The caller is responsible for ensuring that all fields are fully qualified (TABLE.FIELD) and that the table already exists in the query.

The $field, $value and $operator arguments can also be passed in with a single DatabaseCondition object, like this:

Parameters

$group

The WHERE group to add these to; groups are used to create AND/OR sections. Groups cannot be nested. Use 0 as the default group. If the group does not yet exist it will be created as an AND group.

$field

The name of the field to check.

$value

The value to test the field against. In most cases, this is a scalar. For more complex options, it is an array. The meaning of each element in the array is dependent on the $operator.

$operator

The comparison operator, such as =, <, or >=. It also accepts more complex options such as IN, LIKE, LIKE BINARY, or BETWEEN. Defaults to =. If $field is a string you have to use 'formula' here.

See also

ConditionInterface::condition
Condition

addWhereExpression($group, $snippet, $args = [])

Add a complex WHERE clause to the query.

The caller is responsible for ensuring that all fields are fully qualified (TABLE.FIELD) and that the table already exists in the query. Internally the dbtng method "where" is used.

Parameters

$group

The WHERE group to add these to; groups are used to create AND/OR sections. Groups cannot be nested. Use 0 as the default group. If the group does not yet exist it will be created as an AND group.

$snippet

The snippet to check. This can be either a column or a complex expression like "UPPER(table.field) = 'value'"

$args

An associative array of arguments.

See also

\Drupal\views\Plugin\views\query\QueryConditionInterface::where()

addHavingExpression($group, $snippet, $args = [])

Add a complex HAVING clause to the query.

The caller is responsible for ensuring that all fields are fully qualified (TABLE.FIELD) and that the table and an appropriate GROUP BY already exist in the query. Internally the dbtng method "having" is used.

Parameters

$group

The HAVING group to add these to; groups are used to create AND/OR sections. Groups cannot be nested. Use 0 as the default group. If the group does not yet exist it will be created as an AND group.

$snippet

The snippet to check. This can be either a column or a complex expression like "COUNT(table.field) > 3"

$args

An associative array of arguments.

See also

\Drupal\views\Plugin\views\query\QueryConditionInterface::having()

addOrderBy($table, $field = NULL, $order = 'ASC', $alias = '', $params = [])

Add an ORDER BY clause to the query.

Parameters

$table

The table this field is part of. If a formula, enter NULL. If you want to orderby random use "rand" as table and nothing else.

$field

The field or formula to sort on. If already a field, enter NULL and put in the alias.

$order

Either ASC or DESC.

$alias

The alias to add the field as. In SQL, all fields in the order by must also be in the SELECT portion. If an $alias isn't specified one will be generated for from the $field; however, if the $field is a formula, this alias will likely fail.

$params

Any params that should be passed through to the addField.

addGroupBy($clause)

Add a simple GROUP BY clause to the query. The caller is responsible for ensuring that the fields are fully qualified and the table is properly added.

Parameters

$clause

protected getFieldAlias($table_alias, $field)

Returns the alias for the given field added to $table.

Parameters

$table_alias
$field

See also

Sql::addField

addTag($tag)

Adds a query tag to the sql object.

Parameters

$tag

See also

\Drupal\views\Plugin\views\query\SelectQuery::addTag()

placeholder($base = 'views')

Generates a unique placeholder used in the db query.

Parameters

$base

protected buildCondition($where = 'where')

Construct the "WHERE" or "HAVING" part of the query.

As views has to wrap the conditions from arguments with AND, a special group is wrapped around all conditions. This special group has the ID 0. There is other code in filters which makes sure that the group IDs are higher than zero.

Parameters

$where

'where' or 'having'.

protected array getNonAggregates()

Returns a list of non-aggregates to be added to the "group by" clause.

Non-aggregates are fields that have no aggregation function (count, sum, etc) applied. Since the SQL standard requires all fields to either have an aggregation function applied, or to be in the GROUP BY clause, Views gathers those fields and adds them to the GROUP BY clause.

Return Value

array

An array of the fieldnames which are non-aggregates.

protected compileFields(SelectInterface $query)

Adds fields to the query.

Parameters

SelectInterface $query

The drupal query object.

Connection getConnection()

Gets the database connection to use for the view.

The returned database connection does not have to be the default database connection. It can also be to another database connection when the view is to an external database or a replica database.

Return Value

Connection

The database connection to be used for the query.

getWhereArgs()

Get the arguments attached to the WHERE and HAVING clauses of this query.

protected ResultRow[] assignEntitiesToResult(array[] $ids, array $entities, array $results)

Sets entities onto the view result row objects.

This method takes into account the relationship in which the entity was needed in the first place.

Parameters

array[] $ids

A two dimensional array of identifiers (entity ID / revision ID) keyed by relationship.

array $entities

An array of entities keyed by their identified (entity ID / revision ID).

array $results

The entire views result.

Return Value

ResultRow[]

The changed views results.

protected EntityInterface[] getAllEntities()

Gets all the involved entities of the view.

Return Value

EntityInterface[]

aggregationMethodSimple($group_type, $field)

No description

Parameters

$group_type
$field

aggregationMethodDistinct($group_type, $field)

No description

Parameters

$group_type
$field