PHP Class Cake\ORM\Query

See also: Cake\Collection\CollectionInterface For a full description of the collection methods supported by this class
Inheritance: extends Cake\Database\Query, implements JsonSerializabl\JsonSerializable, implements Cake\Datasource\QueryInterface, use trait Cake\Datasource\QueryTrait
Exibir arquivo Open project: cakephp/orm Class Usage Examples

Protected Properties

Property Type Description
$_autoFields boolean Tracks whether or not the original query should include fields from the top level table.
$_beforeFindFired boolean True if the beforeFind event has already been triggered for this query
$_counter callable A callable function that can be used to calculate the total amount of records this query will match when not using limit
$_eagerLoader Cake\ORM\EagerLoader Instance of a class responsible for storing association containments and for eager loading them when this query is executed
$_hasFields boolean Whether the user select any fields before being executed, this is used to determined if any fields should be automatically be selected.
$_hydrate boolean Whether to hydrate results into entity objects
$_resultsCount integer When set, count query execution will be bypassed.

Public Methods

Method Description
__call ( $method, $arguments ) {@inheritDoc}
__clone ( ) : void Object clone hook.
__construct ( Cake\Datasource\ConnectionInterface $connection, Table $table ) Constructor
__debugInfo ( ) {@inheritDoc}
addDefaultTypes ( Table $table ) Hints this object to associate the correct types when casting conditions for the database. This is done by extracting the field types from the schema associated to the passed table object. This prevents the user from repeating himself when specifying conditions.
all ( ) {@inheritDoc}
applyOptions ( array $options ) {@inheritDoc}
autoFields ( boolean | null $value = null ) : boolean | $this Get/Set whether or not the ORM should automatically append fields.
cache ( $key, $config = 'default' ) {@inheritDoc}
cleanCopy ( ) : Query Creates a copy of this current query, triggers beforeFind and resets some state.
contain ( array | string | null $associations = null, boolean $override = false ) : array | $this Sets the list of associations that should be eagerly loaded along with this query. The list of associated tables passed must have been previously set as associations using the Table API.
count ( ) {@inheritDoc}
counter ( callable | null $counter ) Registers a callable function that will be executed when the count method in this query is called. The return value for the function will be set as the return value of the count method.
delete ( string | null $table = null ) Create a delete query.
eagerLoader ( Cake\ORM\EagerLoader $instance = null ) : Cake\ORM\EagerLoader | $this Sets the instance of the eager loader class to use for loading associations and storing containments. If called with no arguments, it will return the currently configured instance.
find ( $finder, array $options = [] ) {@inheritDoc}
hydrate ( boolean | null $enable = null ) : boolean | $this Toggle hydrating entities.
innerJoinWith ( string $assoc, callable $builder = null ) Creates an INNER JOIN with the passed association table while preserving the foreign key matching and the custom conditions that were originally set for it.
insert ( array $columns, array $types = [] ) Create an insert query.
jsonSerialize ( ) : Cake\Datasource\ResultSetInterface Executes the query and converts the result set into JSON.
leftJoinWith ( string $assoc, callable $builder = null ) Creates a LEFT JOIN with the passed association table while preserving the foreign key matching and the custom conditions that were originally set for it.
matching ( string $assoc, callable $builder = null ) Adds filtering conditions to this query to only bring rows that have a relation to another from an associated table, based on conditions in the associated table.
notMatching ( string $assoc, callable $builder = null ) Adds filtering conditions to this query to only bring rows that have no match to another from an associated table, based on conditions in the associated table.
select ( array | Cake\Database\ExpressionInterface | string | Table | Cake\ORM\Association $fields = [], boolean $overwrite = false ) {@inheritDoc}
sql ( ValueBinder $binder = null ) {@inheritDoc}
triggerBeforeFind ( ) : void Trigger the beforeFind event on the query's repository object.
update ( string | null $table = null ) Create an update query.

Protected Methods

Method Description
_addAssociationsToTypeMap ( Table $table, Cake\Database\TypeMap $typeMap, array $associations ) : void Used to recursively add contained association column types to the query.
_addDefaultFields ( ) : void Inspects if there are any set fields for selecting, otherwise adds all the fields for the default table.
_addDefaultSelectTypes ( ) : void Sets the default types for converting the fields in the select clause
_decorateResults ( Traversable $result ) : Cake\Datasource\ResultSetInterface Decorates the results iterator with MapReduce routines and formatters
_dirty ( ) : void Marks a query as dirty, removing any preprocessed information from in memory caching such as previous results
_execute ( ) : Cake\ORM\ResultSet Executes this query and returns a ResultSet object containing the results.
_performCount ( ) : integer Performs and returns the COUNT(*) for the query.
_transformQuery ( ) : void Applies some defaults to the query object before it is executed.

Private Methods

Method Description
_all ( )
_applyDecorators ( )
_cache ( )
_call ( )

Method Details

__call() public method

{@inheritDoc}
public __call ( $method, $arguments )

__clone() public method

Destroys the clones inner iterator and clones the value binder, and eagerloader instances.
public __clone ( ) : void
return void

__construct() public method

Constructor
public __construct ( Cake\Datasource\ConnectionInterface $connection, Table $table )
$connection Cake\Datasource\ConnectionInterface The connection object
$table Table The table this query is starting on

__debugInfo() public method

{@inheritDoc}
public __debugInfo ( )

_addAssociationsToTypeMap() protected method

Used to recursively add contained association column types to the query.
protected _addAssociationsToTypeMap ( Table $table, Cake\Database\TypeMap $typeMap, array $associations ) : void
$table Table The table instance to pluck associations from.
$typeMap Cake\Database\TypeMap The typemap to check for columns in. This typemap is indirectly mutated via Cake\ORM\Query::addDefaultTypes()
$associations array The nested tree of associations to walk.
return void

_addDefaultFields() protected method

Inspects if there are any set fields for selecting, otherwise adds all the fields for the default table.
protected _addDefaultFields ( ) : void
return void

_addDefaultSelectTypes() protected method

Sets the default types for converting the fields in the select clause
protected _addDefaultSelectTypes ( ) : void
return void

_decorateResults() protected method

Decorates the results iterator with MapReduce routines and formatters
protected _decorateResults ( Traversable $result ) : Cake\Datasource\ResultSetInterface
$result Traversable Original results
return Cake\Datasource\ResultSetInterface

_dirty() protected method

Marks a query as dirty, removing any preprocessed information from in memory caching such as previous results
protected _dirty ( ) : void
return void

_execute() protected method

This will also setup the correct statement class in order to eager load deep associations.
protected _execute ( ) : Cake\ORM\ResultSet
return Cake\ORM\ResultSet

_performCount() protected method

Performs and returns the COUNT(*) for the query.
protected _performCount ( ) : integer
return integer

_transformQuery() protected method

Specifically add the FROM clause, adds default table fields if none are specified and applies the joins required to eager load associations defined using contain It also sets the default types for the columns in the select clause
See also: Cake\Database\Query::execute()
protected _transformQuery ( ) : void
return void

addDefaultTypes() public method

This method returns the same query object for chaining.
public addDefaultTypes ( Table $table )
$table Table The table to pull types from

all() public method

{@inheritDoc}
public all ( )

applyOptions() public method

Populates or adds parts to current query clauses using an array. This is handy for passing all query clauses at once. The option array accepts: - fields: Maps to the select method - conditions: Maps to the where method - limit: Maps to the limit method - order: Maps to the order method - offset: Maps to the offset method - group: Maps to the group method - having: Maps to the having method - contain: Maps to the contain options for eager loading - join: Maps to the join method - page: Maps to the page method ### Example: $query->applyOptions([ 'fields' => ['id', 'name'], 'conditions' => [ 'created >=' => '2013-01-01' ], 'limit' => 10 ]); Is equivalent to: $query ->select(['id', 'name']) ->where(['created >=' => '2013-01-01']) ->limit(10)
public applyOptions ( array $options )
$options array

autoFields() public method

By default calling select() will disable auto-fields. You can re-enable auto-fields with this method.
public autoFields ( boolean | null $value = null ) : boolean | $this
$value boolean | null The value to set or null to read the current value.
return boolean | $this Either the current value or the query object.

cache() public method

{@inheritDoc}
public cache ( $key, $config = 'default' )

cleanCopy() public method

The following state will be cleared: - autoFields - limit - offset - map/reduce functions - result formatters - order - containments This method creates query clones that are useful when working with subqueries.
public cleanCopy ( ) : Query
return Query

contain() public method

### Example: Bring articles' author information $query->contain('Author'); Also bring the category and tags associated to each article $query->contain(['Category', 'Tag']); Associations can be arbitrarily nested using dot notation or nested arrays, this allows this object to calculate joins or any additional queries that must be executed to bring the required associated data. ### Example: Eager load the product info, and for each product load other 2 associations $query->contain(['Product' => ['Manufacturer', 'Distributor']); Which is equivalent to calling $query->contain(['Products.Manufactures', 'Products.Distributors']); For an author query, load his region, state and country $query->contain('Regions.States.Countries'); It is possible to control the conditions and fields selected for each of the contained associations: ### Example: $query->contain(['Tags' => function ($q) { return $q->where(['Tags.is_popular' => true]); }]); $query->contain(['Products.Manufactures' => function ($q) { return $q->select(['name'])->where(['Manufactures.active' => true]); }]); Each association might define special options when eager loaded, the allowed options that can be set per association are: - foreignKey: Used to set a different field to match both tables, if set to false no join conditions will be generated automatically. false can only be used on joinable associations and cannot be used with hasMany or belongsToMany associations. - fields: An array with the fields that should be fetched from the association. - finder: The finder to use when loading associated records. Either the name of the finder as a string, or an array to define options to pass to the finder. - queryBuilder: Equivalent to passing a callable instead of an options array. ### Example: Set options for the hasMany articles that will be eagerly loaded for an author $query->contain([ 'Articles' => [ 'fields' => ['title', 'author_id'] ] ]); Finders can be configured to use options. Retrieve translations for the articles, but only those for the en and es locales $query->contain([ 'Articles' => [ 'finder' => [ 'translations' => [ 'locales' => ['en', 'es'] ] ] ] ]); When containing associations, it is important to include foreign key columns. Failing to do so will trigger exceptions. Use special join conditions for getting an Articles's belongsTo 'authors' $query->contain([ 'Authors' => [ 'foreignKey' => false, 'queryBuilder' => function ($q) { return $q->where(...); // Add full filtering conditions } ] ]); If called with no arguments, this function will return an array with with the list of previously configured associations to be contained in the result. If called with an empty first argument and $override is set to true, the previous list will be emptied.
public contain ( array | string | null $associations = null, boolean $override = false ) : array | $this
$associations array | string | null List of table aliases to be queried.
$override boolean Whether override previous list with the one passed defaults to merging previous list with the new one.
return array | $this

count() public method

Returns the COUNT(*) for the query. If the query has not been modified, and the count has already been performed the cached value is returned
public count ( )

counter() public method

This is particularly useful when you need to optimize a query for returning the count, for example removing unnecessary joins, removing group by or just return an estimated number of rows. The callback will receive as first argument a clone of this query and not this query itself. If the first param is a null value, the built-in counter function will be called instead
public counter ( callable | null $counter )
$counter callable | null The counter value

delete() public method

This changes the query type to be 'delete'. Can be combined with the where() method to create delete queries.
public delete ( string | null $table = null )
$table string | null Unused parameter.

eagerLoader() public method

Sets the instance of the eager loader class to use for loading associations and storing containments. If called with no arguments, it will return the currently configured instance.
public eagerLoader ( Cake\ORM\EagerLoader $instance = null ) : Cake\ORM\EagerLoader | $this
$instance Cake\ORM\EagerLoader The eager loader to use. Pass null to get the current eagerloader.
return Cake\ORM\EagerLoader | $this

find() public method

{@inheritDoc}
See also: Cake\ORM\Table::find()
public find ( $finder, array $options = [] )
$options array

hydrate() public method

If set to false array results will be returned
public hydrate ( boolean | null $enable = null ) : boolean | $this
$enable boolean | null Use a boolean to set the hydration mode. Null will fetch the current hydration mode.
return boolean | $this A boolean when reading, and $this when setting the mode.

innerJoinWith() public method

This function will add entries in the contain graph. ### Example: Bring only articles that were tagged with 'cake' $query->innerJoinWith('Tags', function ($q) { return $q->where(['name' => 'cake']); ); This will create the following SQL: SELECT Articles.* FROM articles Articles INNER JOIN tags Tags ON Tags.name = 'cake' INNER JOIN articles_tags ArticlesTags ON ArticlesTags.tag_id = Tags.id AND ArticlesTags.articles_id = Articles.id This function works the same as matching() with the difference that it will select no fields from the association.
See also: Cake\ORM\Query::matching()
public innerJoinWith ( string $assoc, callable $builder = null )
$assoc string The association to join with
$builder callable a function that will receive a pre-made query object that can be used to add custom conditions or selecting some fields

insert() public method

This changes the query type to be 'insert'. Note calling this method will reset any data previously set with Query::values() Can be combined with the where() method to create delete queries.
public insert ( array $columns, array $types = [] )
$columns array The columns to insert into.
$types array A map between columns & their datatypes.

jsonSerialize() public method

Part of JsonSerializable interface.
public jsonSerialize ( ) : Cake\Datasource\ResultSetInterface
return Cake\Datasource\ResultSetInterface The data to convert to JSON.

leftJoinWith() public method

This function will add entries in the contain graph. ### Example: Get the count of articles per user $usersQuery ->select(['total_articles' => $query->func()->count('Articles.id')]) ->leftJoinWith('Articles') ->group(['Users.id']) ->autoFields(true); You can also customize the conditions passed to the LEFT JOIN: Get the count of articles per user with at least 5 votes $usersQuery ->select(['total_articles' => $query->func()->count('Articles.id')]) ->leftJoinWith('Articles', function ($q) { return $q->where(['Articles.votes >=' => 5]); }) ->group(['Users.id']) ->autoFields(true); This will create the following SQL: SELECT COUNT(Articles.id) AS total_articles, Users.* FROM users Users LEFT JOIN articles Articles ON Articles.user_id = Users.id AND Articles.votes >= 5 GROUP BY USers.id It is possible to left join deep associations by using dot notation ### Example: Total comments in articles by 'markstory' $query ->select(['total_comments' => $query->func()->count('Comments.id')]) ->leftJoinWith('Comments.Users', function ($q) { return $q->where(['username' => 'markstory']); ) ->group(['Users.id']); Please note that the query passed to the closure will only accept calling select, where, andWhere and orWhere on it. If you wish to add more complex clauses you can do it directly in the main query.
public leftJoinWith ( string $assoc, callable $builder = null )
$assoc string The association to join with
$builder callable a function that will receive a pre-made query object that can be used to add custom conditions or selecting some fields

matching() public method

This function will add entries in the contain graph. ### Example: Bring only articles that were tagged with 'cake' $query->matching('Tags', function ($q) { return $q->where(['name' => 'cake']); ); It is possible to filter by deep associations by using dot notation: ### Example: Bring only articles that were commented by 'markstory' $query->matching('Comments.Users', function ($q) { return $q->where(['username' => 'markstory']); ); As this function will create INNER JOIN, you might want to consider calling distinct on this query as you might get duplicate rows if your conditions don't filter them already. This might be the case, for example, of the same user commenting more than once in the same article. ### Example: Bring unique articles that were commented by 'markstory' $query->distinct(['Articles.id']) ->matching('Comments.Users', function ($q) { return $q->where(['username' => 'markstory']); ); Please note that the query passed to the closure will only accept calling select, where, andWhere and orWhere on it. If you wish to add more complex clauses you can do it directly in the main query.
public matching ( string $assoc, callable $builder = null )
$assoc string The association to filter by
$builder callable a function that will receive a pre-made query object that can be used to add custom conditions or selecting some fields

notMatching() public method

This function will add entries in the contain graph. ### Example: Bring only articles that were not tagged with 'cake' $query->notMatching('Tags', function ($q) { return $q->where(['name' => 'cake']); ); It is possible to filter by deep associations by using dot notation: ### Example: Bring only articles that weren't commented by 'markstory' $query->notMatching('Comments.Users', function ($q) { return $q->where(['username' => 'markstory']); ); As this function will create a LEFT JOIN, you might want to consider calling distinct on this query as you might get duplicate rows if your conditions don't filter them already. This might be the case, for example, of the same article having multiple comments. ### Example: Bring unique articles that were commented by 'markstory' $query->distinct(['Articles.id']) ->notMatching('Comments.Users', function ($q) { return $q->where(['username' => 'markstory']); ); Please note that the query passed to the closure will only accept calling select, where, andWhere and orWhere on it. If you wish to add more complex clauses you can do it directly in the main query.
public notMatching ( string $assoc, callable $builder = null )
$assoc string The association to filter by
$builder callable a function that will receive a pre-made query object that can be used to add custom conditions or selecting some fields

select() public method

If you pass an instance of a Cake\ORM\Table or Cake\ORM\Association class, all the fields in the schema of the table or the association will be added to the select clause.
public select ( array | Cake\Database\ExpressionInterface | string | Table | Cake\ORM\Association $fields = [], boolean $overwrite = false )
$fields array | Cake\Database\ExpressionInterface | string | Table | Cake\ORM\Association fields to be added to the list.
$overwrite boolean whether to reset fields with passed list or not

sql() public method

{@inheritDoc}
public sql ( ValueBinder $binder = null )
$binder Cake\Database\ValueBinder

triggerBeforeFind() public method

Will not trigger more than once, and only for select queries.
public triggerBeforeFind ( ) : void
return void

update() public method

This changes the query type to be 'update'. Can be combined with set() and where() methods to create update queries.
public update ( string | null $table = null )
$table string | null Unused parameter.

Property Details

$_autoFields protected_oe property

Tracks whether or not the original query should include fields from the top level table.
protected bool $_autoFields
return boolean

$_beforeFindFired protected_oe property

True if the beforeFind event has already been triggered for this query
protected bool $_beforeFindFired
return boolean

$_counter protected_oe property

A callable function that can be used to calculate the total amount of records this query will match when not using limit
protected callable $_counter
return callable

$_eagerLoader protected_oe property

Instance of a class responsible for storing association containments and for eager loading them when this query is executed
protected EagerLoader,Cake\ORM $_eagerLoader
return Cake\ORM\EagerLoader

$_hasFields protected_oe property

Whether the user select any fields before being executed, this is used to determined if any fields should be automatically be selected.
protected bool $_hasFields
return boolean

$_hydrate protected_oe property

Whether to hydrate results into entity objects
protected bool $_hydrate
return boolean

$_resultsCount protected_oe property

When set, count query execution will be bypassed.
protected int $_resultsCount
return integer