DataQuery
class DataQuery (View source)
An object representing a query of data from the DataObject's supporting database.
Acts as a wrapper over SQLSelect and performs all of the query generation. Used extensively by DataList.
Unlike DataList, modifiers on DataQuery modify the object rather than returning a clone. DataList is immutable, DataQuery is mutable.
Traits
Allows an object to have extensions applied to it.
Allows an object to declare a set of custom methods
Properties
| protected static | array | $extra_methods | Custom method sources | from CustomMethods | 
| protected | array | $extra_method_registers | Name of methods to invoke by defineMethods for this instance | from CustomMethods | 
| protected static | array | $built_in_methods | Non-custom public methods. | from CustomMethods | 
| protected | Extension[] | $extension_instances | from Extensible | |
| protected | callable[][] | $beforeExtendCallbacks | List of callbacks to call prior to extensions having extend called on them, each grouped by methodName. | from Extensible | 
| protected | callable[][] | $afterExtendCallbacks | List of callbacks to call after extensions having extend called on them, each grouped by methodName. | from Extensible | 
| protected | string | $dataClass | ||
| protected | SQLSelect | $query | ||
| protected | array | $collidingFields | Map of all field names to an array of conflicting column SQL | |
| protected | DataQueryManipulator[] | $dataQueryManipulators | Allows custom callback to be registered before getFinalisedQuery is called. | |
| protected | $querySubclasses | |||
| protected | $filterByClassName | 
Methods
Attempts to locate and call a method dynamically added to a class at runtime if a default cannot be located
Adds any methods from Extension instances attached to this object.
Register an callback to invoke that defines extra methods
Return TRUE if a method exists on this object
Determines if a custom method with this name is defined.
Get meta-data details on a named method
Return the names of all the methods available on this object
Get all public built in methods for this class
Find all methods on the given object.
Add all the methods from an object property.
Add all the methods from an object property (which is an Extension) to this object.
Add a wrapper method - a method which points to another method with a different name. For example, Thumbnail(x) can be wrapped to generateThumbnail(x)
Add callback as a method.
Allows user code to hook into Object::extend prior to control being delegated to extensions. Each callback will be reset once called.
Allows user code to hook into Object::extend after control being delegated to extensions. Each callback will be reset once called.
Adds any methods from Extension instances attached to this object.
Add an extension to a specific class.
No description
Get extra config sources for this class
Return TRUE if a class has a specified extension.
Calls a method if available on both this object and all applied Extensions, and then attempts to merge all results into an array
Run the given function on all of this object's extensions. Note that this method originally returned void, so if you wanted to return results, you're hosed
Get an extension instance attached to this object by name.
Returns TRUE if this object instance has a specific extension applied in $extension_instances. Extension instances are initialized at constructor time, meaning if you use add_extension() afterwards, the added extension will just be added to new instances of the extended class. Use the static method has_extension() to check if a class (not an instance) has a specific extension.
Get all extension instances for this specific object instance.
Return the SQLSelect object that represents the current query; note that it will be a clone of the object.
Ensure that the query is ready to execute.
Ensure that if a query has an order by clause, those columns are present in the select.
Return whether this dataquery will have records. This will use EXISTS statements in SQL which are more
performant - especially when used in combination with indexed columns (that you're filtering on)
Runs a raw aggregate expression. Please handle escaping yourself
Return the first row that would be returned by this full DataQuery Note that this will issue a separate SELECT ... LIMIT 1 query.
Return the last row that would be returned by this full DataQuery Note that this will issue a separate SELECT ... LIMIT query.
Update the SELECT clause of the query with the columns from the given table
Adds a Common Table Expression (CTE), aka WITH clause.
Set the ORDER BY clause of this query
Add an INNER JOIN clause to this query.
Add a LEFT JOIN clause to this query.
Add a RIGHT JOIN clause to this query.
Prefix of all joined table aliases. E.g. ->filter('Banner.Image.Title)'
Will join the Banner, and then Image relations
$relationPrefx will be banner_image_
Each table in the Image chain will be suffixed to this prefix. E.g.
Traverse the relationship fields, and add the table mappings to the query object state. This has to be called in any overloaded SearchFilter->apply() methods manually.
Join the given has_many relation to this query.
Join the given class to this query with the given key
Join table via many_many relationship
Select the only given fields from the given table.
Add the given fields from the given table to the select statement.
Query the given field column from the database and return as an array.
Select the given field expressions.
Set an arbitrary query parameter, that can be used by decorators to add additional meta-data to the query.
Set an arbitrary query parameter, that can be used by decorators to add additional meta-data to the query.
Assign callback to be invoked in getFinalisedQuery()
Get whether field statements aliased as columns are allowed when that column is already being selected
Set whether field statements aliased as columns are allowed when that column is already being selected
Details
        
                            mixed
    __call(string $method, array $arguments)
        
    
    Attempts to locate and call a method dynamically added to a class at runtime if a default cannot be located
You can add extra methods to a class using Extensions}, {@link Object::createMethod() or Object::addWrapperMethod()
        
                    protected        
    defineMethods()
        
    
    Adds any methods from Extension instances attached to this object.
All these methods can then be called directly on the instance (transparently mapped through __call()}), or called explicitly through {@link extend().
        
                    protected        
    registerExtraMethodCallback(string $name, callable $callback)
        
    
    Register an callback to invoke that defines extra methods
        
                            bool
    hasMethod(string $method)
        
    
    Return TRUE if a method exists on this object
This should be used rather than PHP's inbuild method_exists() as it takes into account methods added via extensions
        
                    protected        bool
    hasCustomMethod($method)
        
    
    Determines if a custom method with this name is defined.
        
                    protected        array
    getExtraMethodConfig(string $method)
        
    
    Get meta-data details on a named method
        
                            array
    allMethodNames(bool $custom = false)
        
    
    Return the names of all the methods available on this object
        
                static    protected        array
    findBuiltInMethods(string|object $class = null)
        
    
    Get all public built in methods for this class
        
                    protected        array
    findMethodsFrom(object $object)
        
    
    Find all methods on the given object.
        
                    protected        
    addMethodsFrom(string $property, string|int $index = null)
        
    
    Add all the methods from an object property.
        
                    protected        
    removeMethodsFrom(string $property, string|int $index = null)
        
    
    Add all the methods from an object property (which is an Extension) to this object.
        
                    protected        
    addWrapperMethod(string $method, string $wrap)
        
    
    Add a wrapper method - a method which points to another method with a different name. For example, Thumbnail(x) can be wrapped to generateThumbnail(x)
        
                    protected        
    addCallbackMethod(string $method, callable $callback)
        
    
    Add callback as a method.
        
                    protected        
    beforeExtending(string $method, callable $callback)
        
    
    Allows user code to hook into Object::extend prior to control being delegated to extensions. Each callback will be reset once called.
        
                    protected        
    afterExtending(string $method, callable $callback)
        
    
    Allows user code to hook into Object::extend after control being delegated to extensions. Each callback will be reset once called.
        
                    protected        
    defineExtensionMethods()
        
    
    Adds any methods from Extension instances attached to this object.
All these methods can then be called directly on the instance (transparently mapped through __call()}), or called explicitly through {@link extend().
        
                static            bool
    add_extension(string $classOrExtension, string $extension = null)
        
    
    Add an extension to a specific class.
The preferred method for adding extensions is through YAML config, since it avoids autoloading the class, and is easier to override in more specific configurations.
As an alternative, extensions can be added to a specific class directly in the Object::$extensions array. See SiteTree::$extensions for examples. Keep in mind that the extension will only be applied to new instances, not existing ones (including all instances created through singleton()).
        
                static            
    remove_extension(string $extension)
        
    
    Remove an extension from a class.
Note: This will not remove extensions from parent classes, and must be called directly on the class assigned the extension.
Keep in mind that this won't revert any datamodel additions of the extension at runtime, unless its used before the schema building kicks in (in your _config.php). Doesn't remove the extension from any Object instances which are already created, but will have an effect on new extensions. Clears any previously created singletons through singleton() to avoid side-effects from stale extension information.
        
                static            array
    get_extensions(string $class = null, bool $includeArgumentString = false)
        
    
    No description
        
                static            array|null
    get_extra_config_sources(string $class = null)
        
    
    Get extra config sources for this class
        
                static            bool
    has_extension(string $classOrExtension, string $requiredExtension = null, bool $strict = false)
        
    
    Return TRUE if a class has a specified extension.
This supports backwards-compatible format (static Object::has_extension($requiredExtension)) and new format ($object->has_extension($class, $requiredExtension))
        
                            array
    invokeWithExtensions(string $method, mixed ...$arguments)
        
    
    Calls a method if available on both this object and all applied Extensions, and then attempts to merge all results into an array
        
                            array
    extend(string $method, mixed ...$arguments)
        
    
    Run the given function on all of this object's extensions. Note that this method originally returned void, so if you wanted to return results, you're hosed
Currently returns an array, with an index resulting every time the function is called. Only adds returns if they're not NULL, to avoid bogus results from methods just defined on the parent extension. This is important for permission-checks through extend, as they use min() to determine if any of the returns is FALSE. As min() doesn't do type checking, an included NULL return would fail the permission checks.
The extension methods are defined during __construct()} in {@link defineMethods().
        
                            Extension|null
    getExtensionInstance(string $extension)
        
    
    Get an extension instance attached to this object by name.
        
                            bool
    hasExtension(string $extension)
        
    
    Returns TRUE if this object instance has a specific extension applied in $extension_instances. Extension instances are initialized at constructor time, meaning if you use add_extension() afterwards, the added extension will just be added to new instances of the extended class. Use the static method has_extension() to check if a class (not an instance) has a specific extension.
Caution: Don't use singleton(
        
                            Extension[]
    getExtensionInstances()
        
    
    Get all extension instances for this specific object instance.
See get_extensions() to get all applied extension classes for this class (not the instance).
This method also provides lazy-population of the extension_instances property.
        
                            
    __construct(string $dataClass)
        
    
    Create a new DataQuery.
        
                            
    __clone()
        
    
    Clone this object
        
                            string
    dataClass()
        
    
    Return the DataObject class that is being queried.
        
                            SQLSelect
    query()
        
    
    Return the SQLSelect object that represents the current query; note that it will be a clone of the object.
        
                            $this
    removeFilterOn(string|array $fieldExpression)
        
    
    Remove a filter from the query
        
                    protected        
    initialiseQuery()
        
    
    Set up the simplest initial query
        
                            $this
    setQueriedColumns(array $queriedColumns)
        
    
    No description
        
                            SQLSelect
    getFinalisedQuery(array|null $queriedColumns = null)
        
    
    Ensure that the query is ready to execute.
        
                    protected        
    ensureSelectContainsOrderbyColumns(SQLSelect $query, array $originalSelect = [])
        
    
    Ensure that if a query has an order by clause, those columns are present in the select.
        
                            Query
    execute()
        
    
    Execute the query and return the result as SS_Query object.
        
                            string
    sql(array $parameters = [])
        
    
    Return this query's SQL
        
                            int
    count()
        
    
    Return the number of records in this query.
Note that this will issue a separate SELECT COUNT() query.
        
                            bool
    exists()
        
    
    Return whether this dataquery will have records. This will use EXISTS statements in SQL which are more
performant - especially when used in combination with indexed columns (that you're filtering on)
        
                            string
    max(string $field)
        
    
    Return the maximum value of the given field in this DataList
        
                            string
    min(string $field)
        
    
    Return the minimum value of the given field in this DataList
        
                            string
    avg(string $field)
        
    
    Return the average value of the given field in this DataList
        
                            string
    sum(string $field)
        
    
    Return the sum of the values of the given field in this DataList
        
                            string
    aggregate(string $expression)
        
    
    Runs a raw aggregate expression. Please handle escaping yourself
        
                            SQLSelect
    firstRow()
        
    
    Return the first row that would be returned by this full DataQuery Note that this will issue a separate SELECT ... LIMIT 1 query.
        
                            SQLSelect
    lastRow()
        
    
    Return the last row that would be returned by this full DataQuery Note that this will issue a separate SELECT ... LIMIT query.
        
                    protected        
    selectColumnsFromTable(SQLSelect $query, string $tableClass, array $columns = null)
        
    
    Update the SELECT clause of the query with the columns from the given table
        
                            $this
    groupby(string $groupby)
        
    
    Append a GROUP BY clause to this query.
        
                            $this
    having(mixed $having)
        
    
    Append a HAVING clause to this query.
        
                            DataQuery
    union(SQLSelect $query, string|null $type = null)
        
    
    Add a query to UNION with.
        
                            DataQuery_SubGroup
    disjunctiveGroup()
        
    
    Create a disjunctive subgroup.
That is a subgroup joined by OR
        
                            DataQuery_SubGroup
    conjunctiveGroup()
        
    
    Create a conjunctive subgroup
That is a subgroup joined by AND
        
                            DataQuery
    with(string $name, SQLSelect $query, array $cteFields = [], bool $recursive = false)
        
    
    Adds a Common Table Expression (CTE), aka WITH clause.
Use of this method should usually be within a conditional check against DB::get_conn()->supportsCteQueries().
        
                            $this
    where(string|array|SQLConditionGroup $filter)
        
    
    Adds a WHERE clause.
        
                            $this
    whereAny(string|array|SQLConditionGroup $filter)
        
    
    Append a WHERE with OR.
        
                            $this
    sort(string $sort = null, string $direction = null, bool $clear = true)
        
    
    Set the ORDER BY clause of this query
Note: while the similarly named DataList::sort() does not allow raw SQL, DataQuery::sort() does allow it
Raw SQL can be vulnerable to SQL injection attacks if used incorrectly, so it's preferable not to use it
        
                            $this
    reverseSort()
        
    
    Reverse order by clause
        
                            DataQuery
    limit(int|null $limit, int $offset = 0)
        
    
    Set the limit of this query.
        
                            $this
    distinct(bool $value)
        
    
    Set whether this query should be distinct or not.
        
                            $this
    innerJoin(string $table, string $onClause, string $alias = null, int $order = 20, array $parameters = [])
        
    
    Add an INNER JOIN clause to this query.
        
                            $this
    leftJoin(string $table, string $onClause, string $alias = null, int $order = 20, array $parameters = [])
        
    
    Add a LEFT JOIN clause to this query.
        
                            $this
    rightJoin(string $table, string $onClause, string $alias = null, int $order = 20, array $parameters = [])
        
    
    Add a RIGHT JOIN clause to this query.
        
                static            string
    applyRelationPrefix(string|array $relation)
        
    
    Prefix of all joined table aliases. E.g. ->filter('Banner.Image.Title)'
Will join the Banner, and then Image relations
$relationPrefx will be banner_image_
Each table in the Image chain will be suffixed to this prefix. E.g.
banner_image_File and banner_image_Image
This will be null if no relation is joined.
E.g. ->filter('Title')
        
                            string
    applyRelation(string|array $relation, bool $linearOnly = false)
        
    
    Traverse the relationship fields, and add the table mappings to the query object state. This has to be called in any overloaded SearchFilter->apply() methods manually.
Note, that in order to filter against the joined relation user code must use {\SilverStripe\ORM\tablePrefix()} to get the table alias used for this relation.
        
                    protected        
    joinHasManyRelation(string $localClass, string $localField, string $foreignClass, string $localPrefix = null, string $foreignPrefix = null, string $type = 'has_many')
        
    
    Join the given has_many relation to this query.
Also works with belongs_to
        
                    protected        
    joinHasOneRelation(string $localClass, string $localField, string $foreignClass, string $localPrefix = null, string $foreignPrefix = null)
        
    
    Join the given class to this query with the given key
        
                    protected        
    joinManyManyRelationship(string $relationClass, string $parentClass, string $componentClass, string $parentField, string $componentField, string $relationClassOrTable, string $parentPrefix = null, string $componentPrefix = null)
        
    
    Join table via many_many relationship
        
                            $this
    subtract(DataQuery $subtractQuery, string $field = 'ID')
        
    
    Removes the result of query from this query.
        
                            $this
    selectFromTable(string $table, array $fields)
        
    
    Select the only given fields from the given table.
        
                            $this
    addSelectFromTable(string $table, array $fields)
        
    
    Add the given fields from the given table to the select statement.
        
                            array
    column(string $field = 'ID')
        
    
    Query the given field column from the database and return as an array.
querying DB columns of related tables is supported but you need to make sure that the related table is already available in join
        
                    protected        string
    expressionForField(string $field)
        
    
    No description
        
                            
    selectField(string $fieldExpression, string $alias = null)
        
    
    Select the given field expressions.
        
                            $this
    setQueryParam(string $key, string|array $value)
        
    
    Set an arbitrary query parameter, that can be used by decorators to add additional meta-data to the query.
It's expected that the $key will be namespaced, e.g, 'Versioned.stage' instead of just 'stage'.
        
                            string
    getQueryParam(string $key)
        
    
    Set an arbitrary query parameter, that can be used by decorators to add additional meta-data to the query.
        
                            array
    getQueryParams()
        
    
    Returns all query parameters
        
                            DataQueryManipulator[]
    getDataQueryManipulators()
        
    
    Get query manipulators
        
                            $this
    pushQueryManipulator(DataQueryManipulator $manipulator)
        
    
    Assign callback to be invoked in getFinalisedQuery()
        
                            bool
    getAllowCollidingFieldStatements()
        
    
    Get whether field statements aliased as columns are allowed when that column is already being selected
        
                            DataQuery
    setAllowCollidingFieldStatements(bool $value)
        
    
    Set whether field statements aliased as columns are allowed when that column is already being selected