PHP Класс Cake\ORM\Query

См. также: Cake\Collection\CollectionInterface For a full description of the collection methods supported by this class
Наследование: extends Cake\Database\Query, implements JsonSerializabl\JsonSerializable, implements Cake\Datasource\QueryInterface, use trait Cake\Datasource\QueryTrait
Показать файл Открыть проект Примеры использования класса

Защищенные свойства (Protected)

Свойство Тип Описание
$_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.

Открытые методы

Метод Описание
__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.

Защищенные методы

Метод Описание
_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.

Приватные методы

Метод Описание
_all ( )
_applyDecorators ( )
_cache ( )
_call ( )

Описание методов

__call() публичный Метод

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

__clone() публичный Метод

Destroys the clones inner iterator and clones the value binder, and eagerloader instances.
public __clone ( ) : void
Результат void

__construct() публичный Метод

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() публичный Метод

{@inheritDoc}
public __debugInfo ( )

_addAssociationsToTypeMap() защищенный Метод

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.
Результат void

_addDefaultFields() защищенный Метод

Inspects if there are any set fields for selecting, otherwise adds all the fields for the default table.
protected _addDefaultFields ( ) : void
Результат void

_addDefaultSelectTypes() защищенный Метод

Sets the default types for converting the fields in the select clause
protected _addDefaultSelectTypes ( ) : void
Результат void

_decorateResults() защищенный Метод

Decorates the results iterator with MapReduce routines and formatters
protected _decorateResults ( Traversable $result ) : Cake\Datasource\ResultSetInterface
$result Traversable Original results
Результат Cake\Datasource\ResultSetInterface

_dirty() защищенный Метод

Marks a query as dirty, removing any preprocessed information from in memory caching such as previous results
protected _dirty ( ) : void
Результат void

_execute() защищенный Метод

This will also setup the correct statement class in order to eager load deep associations.
protected _execute ( ) : Cake\ORM\ResultSet
Результат Cake\ORM\ResultSet

_performCount() защищенный Метод

Performs and returns the COUNT(*) for the query.
protected _performCount ( ) : integer
Результат integer

_transformQuery() защищенный Метод

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
См. также: Cake\Database\Query::execute()
protected _transformQuery ( ) : void
Результат void

addDefaultTypes() публичный Метод

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

all() публичный Метод

{@inheritDoc}
public all ( )

applyOptions() публичный Метод

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() публичный Метод

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.
Результат boolean | $this Either the current value or the query object.

cache() публичный Метод

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

cleanCopy() публичный Метод

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
Результат Query

contain() публичный Метод

### 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.
Результат array | $this

count() публичный Метод

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() публичный Метод

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() публичный Метод

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() публичный Метод

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.
Результат Cake\ORM\EagerLoader | $this

find() публичный Метод

{@inheritDoc}
См. также: Cake\ORM\Table::find()
public find ( $finder, array $options = [] )
$options array

hydrate() публичный Метод

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.
Результат boolean | $this A boolean when reading, and $this when setting the mode.

innerJoinWith() публичный Метод

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.
См. также: 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() публичный Метод

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() публичный Метод

Part of JsonSerializable interface.
public jsonSerialize ( ) : Cake\Datasource\ResultSetInterface
Результат Cake\Datasource\ResultSetInterface The data to convert to JSON.

leftJoinWith() публичный Метод

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() публичный Метод

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() публичный Метод

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() публичный Метод

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() публичный Метод

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

triggerBeforeFind() публичный Метод

Will not trigger more than once, and only for select queries.
public triggerBeforeFind ( ) : void
Результат void

update() публичный Метод

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.

Описание свойств

$_autoFields защищенное свойство

Tracks whether or not the original query should include fields from the top level table.
protected bool $_autoFields
Результат boolean

$_beforeFindFired защищенное свойство

True if the beforeFind event has already been triggered for this query
protected bool $_beforeFindFired
Результат boolean

$_counter защищенное свойство

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
Результат callable

$_eagerLoader защищенное свойство

Instance of a class responsible for storing association containments and for eager loading them when this query is executed
protected EagerLoader,Cake\ORM $_eagerLoader
Результат Cake\ORM\EagerLoader

$_hasFields защищенное свойство

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
Результат boolean

$_hydrate защищенное свойство

Whether to hydrate results into entity objects
protected bool $_hydrate
Результат boolean

$_resultsCount защищенное свойство

When set, count query execution will be bypassed.
protected int $_resultsCount
Результат integer