Query Builder

  • class Cake\ORM\Query
  • The ORM’s query builder provides a simple to use fluent interface for creatingand running queries. By composing queries together, you can create advancedqueries using unions and subqueries with ease.

Underneath the covers, the query builder uses PDO prepared statements whichprotect against SQL injection attacks.

The Query Object

The easiest way to create a Query object is to use find() from aTable object. This method will return an incomplete query ready to bemodified. You can also use a table’s connection object to access the lower levelQuery builder that does not include ORM features, if necessary. See theExecuting Queries section for more information:

  1. use Cake\ORM\TableRegistry;
  2. $articles = TableRegistry::get('Articles');
  3.  
  4. // Start a new query.
  5. $query = $articles->find();

When inside a controller, you can use the automatic table variable that iscreated using the conventions system:

  1. // Inside ArticlesController.php
  2.  
  3. $query = $this->Articles->find();

Selecting Rows From A Table

  1. use Cake\ORM\TableRegistry;
  2.  
  3. $query = TableRegistry::get('Articles')->find();
  4.  
  5. foreach ($query as $article) {
  6. debug($article->title);
  7. }

For the remaining examples, assume that $articles is aORM\Table. When inside controllers, you can use$this->Articles instead of $articles.

Almost every method in a Query object will return the same query, this meansthat Query objects are lazy, and will not be executed unless you tell themto:

  1. $query->where(['id' => 1]); // Return the same query object
  2. $query->order(['title' => 'DESC']); // Still same object, no SQL executed

You can of course chain the methods you call on Query objects:

  1. $query = $articles
  2. ->find()
  3. ->select(['id', 'name'])
  4. ->where(['id !=' => 1])
  5. ->order(['created' => 'DESC']);
  6.  
  7. foreach ($query as $article) {
  8. debug($article->created);
  9. }

If you try to call debug() on a Query object, you will see its internalstate and the SQL that will be executed in the database:

  1. debug($articles->find()->where(['id' => 1]));
  2.  
  3. // Outputs
  4. // ...
  5. // 'sql' => 'SELECT * FROM articles where id = ?'
  6. // ...

You can execute a query directly without having to use foreach on it.The easiest way is to either call the all() or toList() methods:

  1. $resultsIteratorObject = $articles
  2. ->find()
  3. ->where(['id >' => 1])
  4. ->all();
  5.  
  6. foreach ($resultsIteratorObject as $article) {
  7. debug($article->id);
  8. }
  9.  
  10. $resultsArray = $articles
  11. ->find()
  12. ->where(['id >' => 1])
  13. ->toList();
  14.  
  15. foreach ($resultsArray as $article) {
  16. debug($article->id);
  17. }
  18.  
  19. debug($resultsArray[0]->title);

In the above example, $resultsIteratorObject will be an instance ofCake\ORM\ResultSet, an object you can iterate and apply several extractingand traversing methods on.

Often, there is no need to call all(), you can simply iterate theQuery object to get its results. Query objects can also be used directly as theresult object; trying to iterate the query, calling toList() or some of themethods inherited from Collection, willresult in the query being executed and results returned to you.

Selecting A Single Row From A Table

You can use the first() method to get the first result in the query:

  1. $article = $articles
  2. ->find()
  3. ->where(['id' => 1])
  4. ->first();
  5.  
  6. debug($article->title);

Getting A List Of Values From A Column

  1. // Use the extract() method from the collections library
  2. // This executes the query as well
  3. $allTitles = $articles->find()->extract('title');
  4.  
  5. foreach ($allTitles as $title) {
  6. echo $title;
  7. }

You can also get a key-value list out of a query result:

  1. $list = $articles->find('list');
  2.  
  3. foreach ($list as $id => $title) {
  4. echo "$id : $title"
  5. }

For more information on how to customize the fields used for populating the listrefer to Finding Key/Value Pairs section.

Queries Are Collection Objects

Once you get familiar with the Query object methods, it is strongly encouragedthat you visit the Collection section toimprove your skills in efficiently traversing the data. In short, it isimportant to remember that anything you can call on a Collection object, youcan also do in a Query object:

  1. // Use the combine() method from the collections library
  2. // This is equivalent to find('list')
  3. $keyValueList = $articles->find()->combine('id', 'title');
  4.  
  5. // An advanced example
  6. $results = $articles->find()
  7. ->where(['id >' => 1])
  8. ->order(['title' => 'DESC'])
  9. ->map(function ($row) { // map() is a collection method, it executes the query
  10. $row->trimmedTitle = trim($row->title);
  11. return $row;
  12. })
  13. ->combine('id', 'trimmedTitle') // combine() is another collection method
  14. ->toArray(); // Also a collections library method
  15.  
  16. foreach ($results as $id => $trimmedTitle) {
  17. echo "$id : $trimmedTitle";
  18. }

Queries Are Lazily Evaluated

Query objects are lazily evaluated. This means a query is not executed until oneof the following things occur:

  • The query is iterated with foreach().
  • The query’s execute() method is called. This will return the underlyingstatement object, and is to be used with insert/update/delete queries.
  • The query’s first() method is called. This will return the first result in the setbuilt by SELECT (it adds LIMIT 1 to the query).
  • The query’s all() method is called. This will return the result set andcan only be used with SELECT statements.
  • The query’s toList() or toArray() method is called.
    Until one of these conditions are met, the query can be modified without additionalSQL being sent to the database. It also means that if a Query hasn’t beenevaluated, no SQL is ever sent to the database. Once executed, modifying andre-evaluating a query will result in additional SQL being run.

If you want to take a look at what SQL CakePHP is generating, you can turndatabase query logging on.

Selecting Data

CakePHP makes building SELECT queries simple. To limit the fields fetched,you can use the select() method:

  1. $query = $articles->find();
  2. $query->select(['id', 'title', 'body']);
  3. foreach ($query as $row) {
  4. debug($row->title);
  5. }

You can set aliases for fields by providing fields as an associative array:

  1. // Results in SELECT id AS pk, title AS aliased_title, body ...
  2. $query = $articles->find();
  3. $query->select(['pk' => 'id', 'aliased_title' => 'title', 'body']);

To select distinct fields, you can use the distinct() method:

  1. // Results in SELECT DISTINCT country FROM ...
  2. $query = $articles->find();
  3. $query->select(['country'])
  4. ->distinct(['country']);

To set some basic conditions you can use the where() method:

  1. // Conditions are combined with AND
  2. $query = $articles->find();
  3. $query->where(['title' => 'First Post', 'published' => true]);
  4.  
  5. // You can call where() multiple times
  6. $query = $articles->find();
  7. $query->where(['title' => 'First Post'])
  8. ->where(['published' => true]);

You can also pass an anonymous function to the where() method. The passedanonymous function will receive an instance of\Cake\Database\Expression\QueryExpression as its first argument, and\Cake\ORM\Query as its second:

  1. $query = $articles->find();
  2. $query->where(function (QueryExpression $exp, Query $q) {
  3. return $exp->eq('published', true);
  4. });

See the Advanced Conditions section to find out how to constructmore complex WHERE conditions. To apply ordering, you can use the ordermethod:

  1. $query = $articles->find()
  2. ->order(['title' => 'ASC', 'id' => 'ASC']);

When calling order() multiple times on a query, multiple clauses will be appended.However, when using finders you may sometimes need to overwrite the ORDER BY.Set the second parameter of order() (as well as orderAsc() or orderDesc()) toQuery::OVERWRITE or to true:

  1. $query = $articles->find()
  2. ->order(['title' => 'ASC']);
  3. // Later, overwrite the ORDER BY clause instead of appending to it.
  4. $query = $articles->find()
  5. ->order(['created' => 'DESC'], Query::OVERWRITE);

New in version 3.0.12: In addition to order, the orderAsc and orderDesc methods can beused when you need to sort on complex expressions:

  1. $query = $articles->find();
  2. $concat = $query->func()->concat([
  3. 'title' => 'identifier',
  4. 'synopsis' => 'identifier'
  5. ]);
  6. $query->orderAsc($concat);

To limit the number of rows or set the row offset you can use the limit()and page() methods:

  1. // Fetch rows 50 to 100
  2. $query = $articles->find()
  3. ->limit(50)
  4. ->page(2);

As you can see from the examples above, all the methods that modify the queryprovide a fluent interface, allowing you to build a query through chained methodcalls.

Selecting Specific Fields

By default a query will select all fields from a table, the exception is when youcall the select() function yourself and pass certain fields:

  1. // Only select id and title from the articles table
  2. $articles->find()->select(['id', 'title']);

If you wish to still select all fields from a table after having calledselect($fields), you can pass the table instance to select() for thispurpose:

  1. // Only all fields from the articles table including
  2. // a calculated slug field.
  3. $query = $articlesTable->find();
  4. $query
  5. ->select(['slug' => $query->func()->concat(['title' => 'identifier', '-', 'id' => 'identifier'])])
  6. ->select($articlesTable); // Select all fields from articles

New in version 3.1: Passing a table object to select() was added in 3.1.

If you want to select all but a few fields on a table, you can useselectAllExcept():

  1. $query = $articlesTable->find();
  2.  
  3. // Get all fields except the published field.
  4. $query->selectAllExcept($articlesTable, ['published']);

You can also pass an Association object when working with containedassociations.

New in version 3.6.0: The selectAllExcept() method was added.

Using SQL Functions

CakePHP’s ORM offers abstraction for some commonly used SQL functions. Using theabstraction allows the ORM to select the platform specific implementation of thefunction you want. For example, concat is implemented differently in MySQL,PostgreSQL and SQL Server. Using the abstraction allows your code to beportable:

  1. // Results in SELECT COUNT(*) count FROM ...
  2. $query = $articles->find();
  3. $query->select(['count' => $query->func()->count('*')]);

A number of commonly used functions can be created with the func() method:

  • rand() Generate a random value between 0 and 1 via SQL.
  • sum() Calculate a sum. The arguments will be treated as literal values.
  • avg() Calculate an average. The arguments will be treated as literalvalues.
  • min() Calculate the min of a column. The arguments will be treated asliteral values.
  • max() Calculate the max of a column. The arguments will be treated asliteral values.
  • count() Calculate the count. The arguments will be treated as literalvalues.
  • concat() Concatenate two values together. The arguments are treated asbound parameters unless marked as literal.
  • coalesce() Coalesce values. The arguments are treated as bound parametersunless marked as literal.
  • dateDiff() Get the difference between two dates/times. The arguments aretreated as bound parameters unless marked as literal.
  • now() Take either ‘time’ or ‘date’ as an argument allowing you to geteither the current time, or current date.
  • extract() Returns the specified date part from the SQL expression.
  • dateAdd() Add the time unit to the date expression.
  • dayOfWeek() Returns a FunctionExpression representing a call to SQLWEEKDAY function.

New in version 3.1: extract(), dateAdd() and dayOfWeek() methods have been added.

New in version 3.7: rand() was added.

When providing arguments for SQL functions, there are two kinds of parametersyou can use, literal arguments and bound parameters. Identifier/Literal parameters allowyou to reference columns or other SQL literals. Bound parameters can be used tosafely add user data to SQL functions. For example:

  1. $query = $articles->find()->innerJoinWith('Categories');
  2. $concat = $query->func()->concat([
  3. 'Articles.title' => 'identifier',
  4. ' - CAT: ',
  5. 'Categories.name' => 'identifier',
  6. ' - Age: ',
  7. '(DATEDIFF(NOW(), Articles.created))' => 'literal',
  8. ]);
  9. $query->select(['link_title' => $concat]);

By making arguments with a value of literal, the ORM will know thatthe key should be treated as a literal SQL value. By making arguments witha value of identifier, the ORM will know that the key should be treatedas a field identifier. The above would generate the following SQL on MySQL:

  1. SELECT CONCAT(Articles.title, :c0, Categories.name, :c1, (DATEDIFF(NOW(), Articles.created))) FROM articles;

The :c0 value will have the ' - CAT:' text bound when the query isexecuted.

In addition to the above functions, the func() method can be used to createany generic SQL function such as year, date_format, convert, etc.For example:

  1. $query = $articles->find();
  2. $year = $query->func()->year([
  3. 'created' => 'identifier'
  4. ]);
  5. $time = $query->func()->date_format([
  6. 'created' => 'identifier',
  7. "'%H:%i'" => 'literal'
  8. ]);
  9. $query->select([
  10. 'yearCreated' => $year,
  11. 'timeCreated' => $time
  12. ]);

Would result in:

  1. SELECT YEAR(created) as yearCreated, DATE_FORMAT(created, '%H:%i') as timeCreated FROM articles;

You should remember to use the function builder whenever you need to putuntrusted data into SQL functions or stored procedures:

  1. // Use a stored procedure
  2. $query = $articles->find();
  3. $lev = $query->func()->levenshtein([$search, 'LOWER(title)' => 'literal']);
  4. $query->where(function (QueryExpression $exp) use ($lev) {
  5. return $exp->between($lev, 0, $tolerance);
  6. });
  7.  
  8. // Generated SQL would be
  9. WHERE levenshtein(:c0, lower(street)) BETWEEN :c1 AND :c2

Aggregates - Group and Having

When using aggregate functions like count and sum you may want to usegroup by and having clauses:

  1. $query = $articles->find();
  2. $query->select([
  3. 'count' => $query->func()->count('view_count'),
  4. 'published_date' => 'DATE(created)'
  5. ])
  6. ->group('published_date')
  7. ->having(['count >' => 3]);

Case statements

The ORM also offers the SQL case expression. The case expression allowsfor implementing if … then … else logic inside your SQL. This can be usefulfor reporting on data where you need to conditionally sum or count data, or where youneed to specific data based on a condition.

If we wished to know how many published articles are in our database, we could use the following SQL:

  1. SELECT
  2. COUNT(CASE WHEN published = 'Y' THEN 1 END) AS number_published,
  3. COUNT(CASE WHEN published = 'N' THEN 1 END) AS number_unpublished
  4. FROM articles

To do this with the query builder, we’d use the following code:

  1. $query = $articles->find();
  2. $publishedCase = $query->newExpr()
  3. ->addCase(
  4. $query->newExpr()->add(['published' => 'Y']),
  5. 1,
  6. 'integer'
  7. );
  8. $unpublishedCase = $query->newExpr()
  9. ->addCase(
  10. $query->newExpr()->add(['published' => 'N']),
  11. 1,
  12. 'integer'
  13. );
  14.  
  15. $query->select([
  16. 'number_published' => $query->func()->count($publishedCase),
  17. 'number_unpublished' => $query->func()->count($unpublishedCase)
  18. ]);

The addCase function can also chain together multiple statements to createif .. then .. [elseif .. then .. ] [ .. else ] logic inside your SQL.

If we wanted to classify cities into SMALL, MEDIUM, or LARGE based on populationsize, we could do the following:

  1. $query = $cities->find()
  2. ->where(function (QueryExpression $exp, Query $q) {
  3. return $exp->addCase(
  4. [
  5. $q->newExpr()->lt('population', 100000),
  6. $q->newExpr()->between('population', 100000, 999000),
  7. $q->newExpr()->gte('population', 999001),
  8. ],
  9. ['SMALL', 'MEDIUM', 'LARGE'], # values matching conditions
  10. ['string', 'string', 'string'] # type of each value
  11. );
  12. });
  13. # WHERE CASE
  14. # WHEN population < 100000 THEN 'SMALL'
  15. # WHEN population BETWEEN 100000 AND 999000 THEN 'MEDIUM'
  16. # WHEN population >= 999001 THEN 'LARGE'
  17. # END

Any time there are fewer case conditions than values, addCase willautomatically produce an if .. then .. else statement:

  1. $query = $cities->find()
  2. ->where(function (QueryExpression $exp, Query $q) {
  3. return $exp->addCase(
  4. [
  5. $q->newExpr()->eq('population', 0),
  6. ],
  7. ['DESERTED', 'INHABITED'], # values matching conditions
  8. ['string', 'string'] # type of each value
  9. );
  10. });
  11. # WHERE CASE
  12. # WHEN population = 0 THEN 'DESERTED' ELSE 'INHABITED' END

Getting Arrays Instead of Entities

While ORMs and object result sets are powerful, creating entities is sometimesunnecessary. For example, when accessing aggregated data, building an Entity maynot make sense. The process of converting the database results to entities iscalled hydration. If you wish to disable this process you can do this:

  1. $query = $articles->find();
  2. $query->enableHydration(false); // Results as arrays instead of entities
  3. $result = $query->toList(); // Execute the query and return the array

After executing those lines, your result should look similar to this:

  1. [
  2. ['id' => 1, 'title' => 'First Article', 'body' => 'Article 1 body' ...],
  3. ['id' => 2, 'title' => 'Second Article', 'body' => 'Article 2 body' ...],
  4. ...
  5. ]

Adding Calculated Fields

After your queries, you may need to do some post-processing. If you need to adda few calculated fields or derived data, you can use the formatResults()method. This is a lightweight way to map over the result sets. If you need morecontrol over the process, or want to reduce results you should usethe Map/Reduce feature instead. If you were querying a listof people, you could calculate their age with a result formatter:

  1. // Assuming we have built the fields, conditions and containments.
  2. $query->formatResults(function (\Cake\Collection\CollectionInterface $results) {
  3. return $results->map(function ($row) {
  4. $row['age'] = $row['birth_date']->diff(new \DateTime)->y;
  5. return $row;
  6. });
  7. });

As you can see in the example above, formatting callbacks will get aResultSetDecorator as their first argument. The second argument will bethe Query instance the formatter was attached to. The $results argument canbe traversed and modified as necessary.

Result formatters are required to return an iterator object, which will be usedas the return value for the query. Formatter functions are applied after all theMap/Reduce routines have been executed. Result formatters can be applied fromwithin contained associations as well. CakePHP will ensure that your formattersare properly scoped. For example, doing the following would work as you mayexpect:

  1. // In a method in the Articles table
  2. $query->contain(['Authors' => function ($q) {
  3. return $q->formatResults(function (\Cake\Collection\CollectionInterface $authors) {
  4. return $authors->map(function ($author) {
  5. $author['age'] = $author['birth_date']->diff(new \DateTime)->y;
  6. return $author;
  7. });
  8. });
  9. }]);
  10.  
  11. // Get results
  12. $results = $query->all();
  13.  
  14. // Outputs 29
  15. echo $results->first()->author->age;

As seen above, the formatters attached to associated query builders are scopedto operate only on the data in the association. CakePHP will ensure thatcomputed values are inserted into the correct entity.

Advanced Conditions

The query builder makes it simple to build complex where clauses.Grouped conditions can be expressed by providing combining where() andexpression objects. For simple queries, you can build conditions usingan array of conditions:

  1. $query = $articles->find()
  2. ->where([
  3. 'author_id' => 3,
  4. 'OR' => [['view_count' => 2], ['view_count' => 3]],
  5. ]);

The above would generate SQL like:

  1. SELECT * FROM articles WHERE author_id = 3 AND (view_count = 2 OR view_count = 3)

If you’d prefer to avoid deeply nested arrays, you can use the callback form ofwhere() to build your queries. The callback form allows you to use theexpression builder to build more complex conditions without arrays. For example:

  1. $query = $articles->find()->where(function ($exp, $query) {
  2. // Use add() to add multiple conditions for the same field.
  3. $author = $exp->or_(['author_id' => 3])->add(['author_id' => 2]);
  4. $published = $exp->and_(['published' => true, 'view_count' => 10]);
  5.  
  6. return $exp->or_([
  7. 'promoted' => true,
  8. $exp->and_([$author, $published])
  9. ]);
  10. });

The above generates SQL similar to:

  1. SELECT *
  2. FROM articles
  3. WHERE (
  4. (
  5. (author_id = 2 OR author_id = 3)
  6. AND
  7. (published = 1 AND view_count > 10)
  8. )
  9. OR promoted = 1
  10. )

The expression object that is passed into where() functions has two kinds ofmethods. The first type of methods are combinators. The and() andor() methods create new expression objects that change how conditionsare combined. The second type of methods are conditions. Conditions areadded into an expression where they are combined with the current combinator.

For example, calling $exp->and(…) will create a new Expression objectthat combines all conditions it contains with AND. While $exp->or()will create a new Expression object that combines all conditions added to itwith OR. An example of adding conditions with an Expression object wouldbe:

  1. $query = $articles->find()
  2. ->where(function (QueryExpression $exp) {
  3. return $exp
  4. ->eq('author_id', 2)
  5. ->eq('published', true)
  6. ->notEq('spam', true)
  7. ->gt('view_count', 10);
  8. });

Since we started off using where(), we don’t need to call and_(), asthat happens implicitly. The above shows a few new conditionmethods being combined with AND. The resulting SQL would look like:

  1. SELECT *
  2. FROM articles
  3. WHERE (
  4. author_id = 2
  5. AND published = 1
  6. AND spam != 1
  7. AND view_count > 10)

Deprecated since version 3.5.0: As of 3.5.0 the orWhere() method is deprecated. This method createshard to predict SQL based on the current query state.Use where() instead as it has more predictable and easierto understand behavior.

However, if we wanted to use both AND & OR conditions we could do thefollowing:

  1. $query = $articles->find()
  2. ->where(function (QueryExpression $exp) {
  3. $orConditions = $exp->or_(['author_id' => 2])
  4. ->eq('author_id', 5);
  5. return $exp
  6. ->add($orConditions)
  7. ->eq('published', true)
  8. ->gte('view_count', 10);
  9. });

Which would generate the SQL similar to:

  1. SELECT *
  2. FROM articles
  3. WHERE (
  4. (author_id = 2 OR author_id = 5)
  5. AND published = 1
  6. AND view_count >= 10)

The or() and and() methods also allow you to use functions as theirparameters. This is often easier to read than method chaining:

  1. $query = $articles->find()
  2. ->where(function (QueryExpression $exp) {
  3. $orConditions = $exp->or_(function ($or) {
  4. return $or->eq('author_id', 2)
  5. ->eq('author_id', 5);
  6. });
  7. return $exp
  8. ->not($orConditions)
  9. ->lte('view_count', 10);
  10. });

You can negate sub-expressions using not():

  1. $query = $articles->find()
  2. ->where(function (QueryExpression $exp) {
  3. $orConditions = $exp->or_(['author_id' => 2])
  4. ->eq('author_id', 5);
  5. return $exp
  6. ->not($orConditions)
  7. ->lte('view_count', 10);
  8. });

Which will generate the following SQL looking like:

  1. SELECT *
  2. FROM articles
  3. WHERE (
  4. NOT (author_id = 2 OR author_id = 5)
  5. AND view_count <= 10)

It is also possible to build expressions using SQL functions:

  1. $query = $articles->find()
  2. ->where(function (QueryExpression $exp, Query $q) {
  3. $year = $q->func()->year([
  4. 'created' => 'identifier'
  5. ]);
  6. return $exp
  7. ->gte($year, 2014)
  8. ->eq('published', true);
  9. });

Which will generate the following SQL looking like:

  1. SELECT *
  2. FROM articles
  3. WHERE (
  4. YEAR(created) >= 2014
  5. AND published = 1
  6. )

When using the expression objects you can use the following methods to createconditions:

  • eq() Creates an equality condition:
  1. $query = $cities->find()
  2. ->where(function (QueryExpression $exp, Query $q) {
  3. return $exp->eq('population', '10000');
  4. });
  5. # WHERE population = 10000
  • notEq() Creates an inequality condition:
  1. $query = $cities->find()
  2. ->where(function (QueryExpression $exp, Query $q) {
  3. return $exp->notEq('population', '10000');
  4. });
  5. # WHERE population != 10000
  • like() Creates a condition using the LIKE operator:
  1. $query = $cities->find()
  2. ->where(function (QueryExpression $exp, Query $q) {
  3. return $exp->like('name', '%A%');
  4. });
  5. # WHERE name LIKE "%A%"
  • notLike() Creates a negated LIKE condition:
  1. $query = $cities->find()
  2. ->where(function (QueryExpression $exp, Query $q) {
  3. return $exp->notLike('name', '%A%');
  4. });
  5. # WHERE name NOT LIKE "%A%"
  • in() Create a condition using IN:
  1. $query = $cities->find()
  2. ->where(function (QueryExpression $exp, Query $q) {
  3. return $exp->in('country_id', ['AFG', 'USA', 'EST']);
  4. });
  5. # WHERE country_id IN ('AFG', 'USA', 'EST')
  • notIn() Create a negated condition using IN:
  1. $query = $cities->find()
  2. ->where(function (QueryExpression $exp, Query $q) {
  3. return $exp->notIn('country_id', ['AFG', 'USA', 'EST']);
  4. });
  5. # WHERE country_id NOT IN ('AFG', 'USA', 'EST')
  • gt() Create a > condition:
  1. $query = $cities->find()
  2. ->where(function (QueryExpression $exp, Query $q) {
  3. return $exp->gt('population', '10000');
  4. });
  5. # WHERE population > 10000
  • gte() Create a >= condition:
  1. $query = $cities->find()
  2. ->where(function (QueryExpression $exp, Query $q) {
  3. return $exp->gte('population', '10000');
  4. });
  5. # WHERE population >= 10000
  • lt() Create a < condition:
  1. $query = $cities->find()
  2. ->where(function (QueryExpression $exp, Query $q) {
  3. return $exp->lt('population', '10000');
  4. });
  5. # WHERE population < 10000
  • lte() Create a <= condition:
  1. $query = $cities->find()
  2. ->where(function (QueryExpression $exp, Query $q) {
  3. return $exp->lte('population', '10000');
  4. });
  5. # WHERE population <= 10000
  • isNull() Create an IS NULL condition:
  1. $query = $cities->find()
  2. ->where(function (QueryExpression $exp, Query $q) {
  3. return $exp->isNull('population');
  4. });
  5. # WHERE (population) IS NULL
  • isNotNull() Create a negated IS NULL condition:
  1. $query = $cities->find()
  2. ->where(function (QueryExpression $exp, Query $q) {
  3. return $exp->isNotNull('population');
  4. });
  5. # WHERE (population) IS NOT NULL
  • between() Create a BETWEEN condition:
  1. $query = $cities->find()
  2. ->where(function (QueryExpression $exp, Query $q) {
  3. return $exp->between('population', 999, 5000000);
  4. });
  5. # WHERE population BETWEEN 999 AND 5000000,
  • exists() Create a condition using EXISTS:
  1. $subquery = $cities->find()
  2. ->select(['id'])
  3. ->where(function (QueryExpression $exp, Query $q) {
  4. return $exp->equalFields('countries.id', 'cities.country_id');
  5. })
  6. ->andWhere(['population >' => 5000000]);
  7.  
  8. $query = $countries->find()
  9. ->where(function (QueryExpression $exp, Query $q) use ($subquery) {
  10. return $exp->exists($subquery);
  11. });
  12. # WHERE EXISTS (SELECT id FROM cities WHERE countries.id = cities.country_id AND population > 5000000)
  • notExists() Create a negated condition using EXISTS:
  1. $subquery = $cities->find()
  2. ->select(['id'])
  3. ->where(function (QueryExpression $exp, Query $q) {
  4. return $exp->equalFields('countries.id', 'cities.country_id');
  5. })
  6. ->andWhere(['population >' => 5000000]);
  7.  
  8. $query = $countries->find()
  9. ->where(function (QueryExpression $exp, Query $q) use ($subquery) {
  10. return $exp->notExists($subquery);
  11. });
  12. # WHERE NOT EXISTS (SELECT id FROM cities WHERE countries.id = cities.country_id AND population > 5000000)

In situations when you can’t get, or don’t want to use the builder methods tocreate the conditions you want you can also use snippets of SQL in whereclauses:

  1. // Compare two fields to each other
  2. $query->where(['Categories.parent_id != Parents.id']);

Warning

The field names used in expressions, and SQL snippets should nevercontain untrusted content. See the Using SQL Functions section forhow to safely include unsafe data into function calls.

Using Identifiers in Expressions

When you need to reference a column or SQL identifier in your queries you canuse the identifier() method:

  1. $query = $countries->find();
  2. $query->select([
  3. 'year' => $query->func()->year([$query->identifier('created')])
  4. ])
  5. ->where(function ($exp, $query) {
  6. return $exp->gt('population', 100000);
  7. });

Warning

To prevent SQL injections, Identifier expressions should never haveuntrusted data passed into them.

New in version 3.6.0: Query::identifier() was added in 3.6.0

Automatically Creating IN Clauses

When building queries using the ORM, you will generally not have to indicate thedata types of the columns you are interacting with, as CakePHP can infer thetypes based on the schema data. If in your queries you’d like CakePHP toautomatically convert equality to IN comparisons, you’ll need to indicatethe column data type:

  1. $query = $articles->find()
  2. ->where(['id' => $ids], ['id' => 'integer[]']);
  3.  
  4. // Or include IN to automatically cast to an array.
  5. $query = $articles->find()
  6. ->where(['id IN' => $ids]);

The above will automatically create id IN (…) instead of id = ?. Thiscan be useful when you do not know whether you will get a scalar or array ofparameters. The [] suffix on any data type name indicates to the querybuilder that you want the data handled as an array. If the data is not an array,it will first be cast to an array. After that, each value in the array willbe cast using the type system. This works withcomplex types as well. For example, you could take a list of DateTime objectsusing:

  1. $query = $articles->find()
  2. ->where(['post_date' => $dates], ['post_date' => 'date[]']);

Automatic IS NULL Creation

When a condition value is expected to be null or any other value, you canuse the IS operator to automatically create the correct expression:

  1. $query = $categories->find()
  2. ->where(['parent_id IS' => $parentId]);

The above will create parent_id` = :c1 or parent_id IS NULL depending onthe type of $parentId

Automatic IS NOT NULL Creation

When a condition value is expected not to be null or any other value, youcan use the IS NOT operator to automatically create the correct expression:

  1. $query = $categories->find()
  2. ->where(['parent_id IS NOT' => $parentId]);

The above will create parent_id` != :c1 or parent_id IS NOT NULLdepending on the type of $parentId

Raw Expressions

When you cannot construct the SQL you need using the query builder, you can useexpression objects to add snippets of SQL to your queries:

  1. $query = $articles->find();
  2. $expr = $query->newExpr()->add('1 + 1');
  3. $query->select(['two' => $expr]);

Expression objects can be used with any query builder methods likewhere(), limit(), group(), select() and many other methods.

Warning

Using expression objects leaves you vulnerable to SQL injection. You shouldnever use untrusted data into expressions.

Getting Results

Once you’ve made your query, you’ll want to retrieve rows from it. There area few ways of doing this:

  1. // Iterate the query
  2. foreach ($query as $row) {
  3. // Do stuff.
  4. }
  5.  
  6. // Get the results
  7. $results = $query->all();

You can use any of the collection methodson your query objects to pre-process or transform the results:

  1. // Use one of the collection methods.
  2. $ids = $query->map(function ($row) {
  3. return $row->id;
  4. });
  5.  
  6. $maxAge = $query->max(function ($max) {
  7. return $max->age;
  8. });

You can use first or firstOrFail to retrieve a single record. Thesemethods will alter the query adding a LIMIT 1 clause:

  1. // Get just the first row
  2. $row = $query->first();
  3.  
  4. // Get the first row or an exception.
  5. $row = $query->firstOrFail();

Returning the Total Count of Records

Using a single query object, it is possible to obtain the total number of rowsfound for a set of conditions:

  1. $total = $articles->find()->where(['is_active' => true])->count();

The count() method will ignore the limit, offset and pageclauses, thus the following will return the same result:

  1. $total = $articles->find()->where(['is_active' => true])->limit(10)->count();

This is useful when you need to know the total result set size in advance,without having to construct another Query object. Likewise, all resultformatting and map-reduce routines are ignored when using the count()method.

Moreover, it is possible to return the total count for a query containing groupby clauses without having to rewrite the query in any way. For example, considerthis query for retrieving article ids and their comments count:

  1. $query = $articles->find();
  2. $query->select(['Articles.id', $query->func()->count('Comments.id')])
  3. ->matching('Comments')
  4. ->group(['Articles.id']);
  5. $total = $query->count();

After counting, the query can still be used for fetching the associatedrecords:

  1. $list = $query->all();

Sometimes, you may want to provide an alternate method for counting the totalrecords of a query. One common use case for this is providinga cached value or an estimate of the total rows, or to alter the query to removeexpensive unneeded parts such as left joins. This becomes particularly handywhen using the CakePHP built-in pagination system which calls the count()method:

  1. $query = $query->where(['is_active' => true])->counter(function ($query) {
  2. return 100000;
  3. });
  4. $query->count(); // Returns 100000

In the example above, when the pagination component calls the count method, itwill receive the estimated hard-coded number of rows.

Caching Loaded Results

When fetching entities that don’t change often you may want to cache theresults. The Query class makes this simple:

  1. $query->cache('recent_articles');

Will enable caching on the query’s result set. If only one argument is providedto cache() then the ‘default’ cache configuration will be used. You cancontrol which caching configuration is used with the second parameter:

  1. // String config name.
  2. $query->cache('recent_articles', 'dbResults');
  3.  
  4. // Instance of CacheEngine
  5. $query->cache('recent_articles', $memcache);

In addition to supporting static keys, the cache() method accepts a functionto generate the key. The function you give it will receive the query as anargument. You can then read aspects of the query to dynamically generate thecache key:

  1. // Generate a key based on a simple checksum
  2. // of the query's where clause
  3. $query->cache(function ($q) {
  4. return 'articles-' . md5(serialize($q->clause('where')));
  5. });

The cache method makes it simple to add cached results to your custom finders orthrough event listeners.

When the results for a cached query are fetched the following happens:

  • The Model.beforeFind event is triggered.
  • If the query has results set, those will be returned.
  • The cache key will be resolved and cache data will be read. If the cache datais not empty, those results will be returned.
  • If the cache misses, the query will be executed and a new ResultSet will becreated. This ResultSet will be written to the cache and returned.

Note

You cannot cache a streaming query result.

Loading Associations

The builder can help you retrieve data from multiple tables at the same timewith the minimum amount of queries possible. To be able to fetch associateddata, you first need to setup associations between the tables as described inthe Associations - Linking Tables Together section. This technique of combining queriesto fetch associated data from other tables is called eager loading.

Eager loading helps avoid many of the potential performance problemssurrounding lazy-loading in an ORM. The queries generated by eager loading canbetter leverage joins, allowing more efficient queries to be made. In CakePHPyou define eager loaded associations using the ‘contain’ method:

  1. // In a controller or table method.
  2.  
  3. // As an option to find()
  4. $query = $articles->find('all', ['contain' => ['Authors', 'Comments']]);
  5.  
  6. // As a method on the query object
  7. $query = $articles->find('all');
  8. $query->contain(['Authors', 'Comments']);

The above will load the related author and comments for each article in theresult set. You can load nested associations using nested arrays to define theassociations to be loaded:

  1. $query = $articles->find()->contain([
  2. 'Authors' => ['Addresses'], 'Comments' => ['Authors']
  3. ]);

Alternatively, you can express nested associations using the dot notation:

  1. $query = $articles->find()->contain([
  2. 'Authors.Addresses',
  3. 'Comments.Authors'
  4. ]);

You can eager load associations as deep as you like:

  1. $query = $products->find()->contain([
  2. 'Shops.Cities.Countries',
  3. 'Shops.Managers'
  4. ]);

You can select fields from all associations with multiple easy contain()statements:

  1. $query = $this->find()->select([
  2. 'Realestates.id',
  3. 'Realestates.title',
  4. 'Realestates.description'
  5. ])
  6. ->contain([
  7. 'RealestateAttributes' => [
  8. 'Attributes' => [
  9. 'fields' => [
  10. // Aliased fields in contain() must include
  11. // the model prefix to be mapped correctly.
  12. 'Attributes__name' => 'attr_name'
  13. ]
  14. ]
  15. ]
  16. ])
  17. ->contain([
  18. 'RealestateAttributes' => [
  19. 'fields' => [
  20. 'RealestateAttributes.realestate_id',
  21. 'RealestateAttributes.value'
  22. ]
  23. ]
  24. ])
  25. ->where($condition);

If you need to reset the containments on a query you can set the second argumentto true:

  1. $query = $articles->find();
  2. $query->contain(['Authors', 'Comments'], true);

Passing Conditions to Contain

When using contain() you are able to restrict the data returned by theassociations and filter them by conditions. To specify conditions, pass an anonymousfunction that receives as the first argument a query object, \Cake\ORM\Query:

  1. // In a controller or table method.
  2. // Prior to 3.5.0 you would use contain(['Comments' => function () { ... }])
  3.  
  4. $query = $articles->find()->contain('Comments', function (Query $q) {
  5. return $q
  6. ->select(['body', 'author_id'])
  7. ->where(['Comments.approved' => true]);
  8. });

This also works for pagination at the Controller level:

  1. $this->paginate['contain'] = [
  2. 'Comments' => function (Query $query) {
  3. return $query->select(['body', 'author_id'])
  4. ->where(['Comments.approved' => true]);
  5. }
  6. ];

Note

When you limit the fields that are fetched from an association, you mustensure that the foreign key columns are selected. Failing to select foreignkey fields will cause associated data to not be present in the final result.

It is also possible to restrict deeply-nested associations using the dotnotation:

  1. $query = $articles->find()->contain([
  2. 'Comments',
  3. 'Authors.Profiles' => function (Query $q) {
  4. return $q->where(['Profiles.is_published' => true]);
  5. }
  6. ]);

In the above example, you’ll still get authors even if they don’t havea published profile. To only get authors with a published profile usematching(). If you have defined customfinders in your associations, you can use them inside contain():

  1. // Bring all articles, but only bring the comments that are approved and
  2. // popular.
  3. $query = $articles->find()->contain('Comments', function (Query $q) {
  4. return $q->find('approved')->find('popular');
  5. });

Note

For BelongsTo and HasOne associations only the where andselect clauses are used when loading the associated records. For therest of the association types you can use every clause that the query objectprovides.

If you need full control over the query that is generated, you can tell contain()to not append the foreignKey constraints to the generated query. In thatcase you should use an array passing foreignKey and queryBuilder:

  1. $query = $articles->find()->contain([
  2. 'Authors' => [
  3. 'foreignKey' => false,
  4. 'queryBuilder' => function (Query $q) {
  5. return $q->where(...); // Full conditions for filtering
  6. }
  7. ]
  8. ]);

If you have limited the fields you are loading with select() but also want toload fields off of contained associations, you can pass the association objectto select():

  1. // Select id & title from articles, but all fields off of Users.
  2. $query = $articles->find()
  3. ->select(['id', 'title'])
  4. ->select($articles->Users)
  5. ->contain(['Users']);

Alternatively, if you have multiple associations, you can use enableAutoFields():

  1. // Select id & title from articles, but all fields off of Users, Comments
  2. // and Tags.
  3. $query->select(['id', 'title'])
  4. ->contain(['Comments', 'Tags'])
  5. ->enableAutoFields(true) // Prior to 3.4.0 use autoFields(true)
  6. ->contain(['Users' => function(Query $q) {
  7. return $q->autoFields(true);
  8. }]);

New in version 3.1: Selecting columns via an association object was added in 3.1

Sorting Contained Associations

When loading HasMany and BelongsToMany associations, you can use the sortoption to sort the data in those associations:

  1. $query->contain([
  2. 'Comments' => [
  3. 'sort' => ['Comments.created' => 'DESC']
  4. ]
  5. ]);

Filtering by Associated Data

A fairly common query case with associations is finding records ‘matching’specific associated data. For example if you have ‘Articles belongsToMany Tags’you will probably want to find Articles that have the CakePHP tag. This isextremely simple to do with the ORM in CakePHP:

  1. // In a controller or table method.
  2.  
  3. $query = $articles->find();
  4. $query->matching('Tags', function ($q) {
  5. return $q->where(['Tags.name' => 'CakePHP']);
  6. });

You can apply this strategy to HasMany associations as well. For example if‘Authors HasMany Articles’, you could find all the authors with recentlypublished articles using the following:

  1. $query = $authors->find();
  2. $query->matching('Articles', function ($q) {
  3. return $q->where(['Articles.created >=' => new DateTime('-10 days')]);
  4. });

Filtering by deep associations is surprisingly easy, and the syntax should bealready familiar to you:

  1. // In a controller or table method.
  2. $query = $products->find()->matching(
  3. 'Shops.Cities.Countries', function ($q) {
  4. return $q->where(['Countries.name' => 'Japan']);
  5. }
  6. );
  7.  
  8. // Bring unique articles that were commented by 'markstory' using passed variable
  9. // Dotted matching paths should be used over nested matching() calls
  10. $username = 'markstory';
  11. $query = $articles->find()->matching('Comments.Users', function ($q) use ($username) {
  12. return $q->where(['username' => $username]);
  13. });

Note

As this function will create an INNER JOIN, you might want to considercalling distinct on the find query as you might get duplicate rows ifyour conditions don’t exclude them already. This might be the case, forexample, when the same users comments more than once on a single article.

The data from the association that is ‘matched’ will be available on the_matchingData property of entities. If both match and contain the sameassociation, you can expect to get both the _matchingData and standardassociation properties in your results.

Using innerJoinWith

Using the matching() function, as we saw already, will create an INNER
JOIN
with the specified association and will also load the fields into theresult set.

There may be cases where you want to use matching() but are not interestedin loading the fields into the result set. For this purpose, you can useinnerJoinWith():

  1. $query = $articles->find();
  2. $query->innerJoinWith('Tags', function ($q) {
  3. return $q->where(['Tags.name' => 'CakePHP']);
  4. });

The innerJoinWith() method works the same as matching(), thatmeans that you can use dot notation to join deeply nestedassociations:

  1. $query = $products->find()->innerJoinWith(
  2. 'Shops.Cities.Countries', function ($q) {
  3. return $q->where(['Countries.name' => 'Japan']);
  4. }
  5. );

Again, the only difference is that no additional columns will be added to theresult set, and no _matchingData property will be set.However, it is possible to combine innerJoinWith() and contain() when you need to filter by associate data and you want also to retrieve associate fields too (following the same filter):

  1. $filter = ['Tags.name' => 'CakePHP'];
  2. $query = $articles->find()
  3. ->distinct($articles)
  4. ->contain('Tags', function (\Cake\ORM\Query $q) use ($filter) {
  5. return $q->where($filter);
  6. })
  7. ->innerJoinWith('Tags', function (\Cake\ORM\Query $q) use ($filter) {
  8. return $q->where($filter);
  9. });

New in version 3.1: Query::innerJoinWith() was added in 3.1

Using notMatching

The opposite of matching() is notMatching(). This function will changethe query so that it filters results that have no relation to the specifiedassociation:

  1. // In a controller or table method.
  2.  
  3. $query = $articlesTable
  4. ->find()
  5. ->notMatching('Tags', function ($q) {
  6. return $q->where(['Tags.name' => 'boring']);
  7. });

The above example will find all articles that were not tagged with the wordboring. You can apply this method to HasMany associations as well. You could,for example, find all the authors with no published articles in the last 10days:

  1. $query = $authorsTable
  2. ->find()
  3. ->notMatching('Articles', function ($q) {
  4. return $q->where(['Articles.created >=' => new \DateTime('-10 days')]);
  5. });

It is also possible to use this method for filtering out records not matchingdeep associations. For example, you could find articles that have not beencommented on by a certain user:

  1. $query = $articlesTable
  2. ->find()
  3. ->notMatching('Comments.Users', function ($q) {
  4. return $q->where(['username' => 'jose']);
  5. });

Since articles with no comments at all also satisfy the condition above, you maywant to combine matching() and notMatching() in the same query. Thefollowing example will find articles having at least one comment, but notcommented by a certain user:

  1. $query = $articlesTable
  2. ->find()
  3. ->notMatching('Comments.Users', function ($q) {
  4. return $q->where(['username' => 'jose']);
  5. })
  6. ->matching('Comments');

Note

As notMatching() will create a LEFT JOIN, you might want to considercalling distinct on the find query as you can get duplicate rowsotherwise.

Keep in mind that contrary to the matching() function, notMatching()will not add any data to the _matchingData property in the results.

New in version 3.1: Query::notMatching() was added in 3.1

Using leftJoinWith

On certain occasions you may want to calculate a result based on an association,without having to load all the records for it. For example, if you wanted toload the total number of comments an article has along with all the articledata, you can use the leftJoinWith() function:

  1. $query = $articlesTable->find();
  2. $query->select(['total_comments' => $query->func()->count('Comments.id')])
  3. ->leftJoinWith('Comments')
  4. ->group(['Articles.id'])
  5. ->enableAutoFields(true); // Prior to 3.4.0 use autoFields(true);

The results for the above query will contain the article data and thetotal_comments property for each of them.

leftJoinWith() can also be used with deeply nested associations. This isuseful, for example, for bringing the count of articles tagged with a certainword, per author:

  1. $query = $authorsTable
  2. ->find()
  3. ->select(['total_articles' => $query->func()->count('Articles.id')])
  4. ->leftJoinWith('Articles.Tags', function ($q) {
  5. return $q->where(['Tags.name' => 'awesome']);
  6. })
  7. ->group(['Authors.id'])
  8. ->enableAutoFields(true); // Prior to 3.4.0 use autoFields(true);

This function will not load any columns from the specified associations into theresult set.

New in version 3.1: Query::leftJoinWith() was added in 3.1

Adding Joins

In addition to loading related data with contain(), you can also addadditional joins with the query builder:

  1. $query = $articles->find()
  2. ->join([
  3. 'table' => 'comments',
  4. 'alias' => 'c',
  5. 'type' => 'LEFT',
  6. 'conditions' => 'c.article_id = articles.id',
  7. ]);

You can append multiple joins at the same time by passing an associative arraywith multiple joins:

  1. $query = $articles->find()
  2. ->join([
  3. 'c' => [
  4. 'table' => 'comments',
  5. 'type' => 'LEFT',
  6. 'conditions' => 'c.article_id = articles.id',
  7. ],
  8. 'u' => [
  9. 'table' => 'users',
  10. 'type' => 'INNER',
  11. 'conditions' => 'u.id = articles.user_id',
  12. ]
  13. ]);

As seen above, when adding joins the alias can be the outer array key. Joinconditions can also be expressed as an array of conditions:

  1. $query = $articles->find()
  2. ->join([
  3. 'c' => [
  4. 'table' => 'comments',
  5. 'type' => 'LEFT',
  6. 'conditions' => [
  7. 'c.created >' => new DateTime('-5 days'),
  8. 'c.moderated' => true,
  9. 'c.article_id = articles.id'
  10. ]
  11. ],
  12. ], ['c.created' => 'datetime', 'c.moderated' => 'boolean']);

When creating joins by hand and using array based conditions, you need toprovide the datatypes for each column in the join conditions. By providingdatatypes for the join conditions, the ORM can correctly convert data types intoSQL. In addition to join() you can use rightJoin(), leftJoin() andinnerJoin() to create joins:

  1. // Join with an alias and string conditions
  2. $query = $articles->find();
  3. $query->leftJoin(
  4. ['Authors' => 'authors'],
  5. ['Authors.id = Articles.author_id']);
  6.  
  7. // Join with an alias, array conditions, and types
  8. $query = $articles->find();
  9. $query->innerJoin(
  10. ['Authors' => 'authors'],
  11. [
  12. 'Authors.promoted' => true,
  13. 'Authors.created' => new DateTime('-5 days'),
  14. 'Authors.id = Articles.author_id'
  15. ],
  16. ['Authors.promoted' => 'boolean', 'Authors.created' => 'datetime']);

It should be noted that if you set the quoteIdentifiers option to true whendefining your Connection, join conditions between table fields should be set as follow:

  1. $query = $articles->find()
  2. ->join([
  3. 'c' => [
  4. 'table' => 'comments',
  5. 'type' => 'LEFT',
  6. 'conditions' => [
  7. 'c.article_id' => new \Cake\Database\Expression\IdentifierExpression('articles.id')
  8. ]
  9. ],
  10. ]);

This ensures that all of your identifiers will be quoted across the Query, avoiding errors withsome database Drivers (PostgreSQL notably)

Inserting Data

Unlike earlier examples, you should not use find() to create insert queries.Instead, create a new Query object using query():

  1. $query = $articles->query();
  2. $query->insert(['title', 'body'])
  3. ->values([
  4. 'title' => 'First post',
  5. 'body' => 'Some body text'
  6. ])
  7. ->execute();

To insert multiple rows with only one query, you can chain the values()method as many times as you need:

  1. $query = $articles->query();
  2. $query->insert(['title', 'body'])
  3. ->values([
  4. 'title' => 'First post',
  5. 'body' => 'Some body text'
  6. ])
  7. ->values([
  8. 'title' => 'Second post',
  9. 'body' => 'Another body text'
  10. ])
  11. ->execute();

Generally, it is easier to insert data using entities andORM\Table::save(). By composing a SELECT andINSERT query together, you can create INSERT INTO … SELECT stylequeries:

  1. $select = $articles->find()
  2. ->select(['title', 'body', 'published'])
  3. ->where(['id' => 3]);
  4.  
  5. $query = $articles->query()
  6. ->insert(['title', 'body', 'published'])
  7. ->values($select)
  8. ->execute();

Note

Inserting records with the query builder will not trigger events such asModel.afterSave. Instead you should use the ORM to savedata.

Updating Data

As with insert queries, you should not use find() to create update queries.Instead, create new a Query object using query():

  1. $query = $articles->query();
  2. $query->update()
  3. ->set(['published' => true])
  4. ->where(['id' => $id])
  5. ->execute();

Generally, it is easier to update data using entities andORM\Table::patchEntity().

Note

Updating records with the query builder will not trigger events such asModel.afterSave. Instead you should use the ORM to savedata.

Deleting Data

As with insert queries, you should not use find() to create delete queries.Instead, create new a query object using query():

  1. $query = $articles->query();
  2. $query->delete()
  3. ->where(['id' => $id])
  4. ->execute();

Generally, it is easier to delete data using entities andORM\Table::delete().

SQL Injection Prevention

While the ORM and database abstraction layers prevent most SQL injectionsissues, it is still possible to leave yourself vulnerable through improper use.

When using condition arrays, the key/left-hand side as well as single valueentries must not contain user data:

  1. $query->where([
  2. // Data on the key/left-hand side is unsafe, as it will be
  3. // inserted into the generated query as-is
  4. $userData => $value,
  5.  
  6. // The same applies to single value entries, they are not
  7. // safe to use with user data in any form
  8. $userData,
  9. "MATCH (comment) AGAINST ($userData)",
  10. 'created < NOW() - ' . $userData
  11. ]);

When using the expression builder, column names must not contain user data:

  1. $query->where(function (QueryExpression $exp) use ($userData, $values) {
  2. // Column names in all expressions are not safe.
  3. return $exp->in($userData, $values);
  4. });

When building function expressions, function names should never contain userdata:

  1. // Not safe.
  2. $query->func()->{$userData}($arg1);
  3.  
  4. // Also not safe to use an array of
  5. // user data in a function expression
  6. $query->func()->coalesce($userData);

Raw expressions are never safe:

  1. $expr = $query->newExpr()->add($userData);
  2. $query->select(['two' => $expr]);

Binding values

It is possible to protect against many unsafe situations by using bindings.Similar to binding values to prepared statements,values can be bound to queries using the Cake\Database\Query::bind()method.

The following example would be a safe variant of the unsafe, SQL injection proneexample given above:

  1. $query
  2. ->where([
  3. 'MATCH (comment) AGAINST (:userData)',
  4. 'created < NOW() - :moreUserData'
  5. ])
  6. ->bind(':userData', $userData, 'string')
  7. ->bind(':moreUserData', $moreUserData, 'datetime');

Note

Unlike Cake\Database\StatementInterface::bindValue(),Query::bind() requires to pass the named placeholders including thecolon!

More Complex Queries

The query builder is capable of building complex queries like UNION queriesand sub-queries.

Unions

Unions are created by composing one or more select queries together:

  1. $inReview = $articles->find()
  2. ->where(['need_review' => true]);
  3.  
  4. $unpublished = $articles->find()
  5. ->where(['published' => false]);
  6.  
  7. $unpublished->union($inReview);

You can create UNION ALL queries using the unionAll() method:

  1. $inReview = $articles->find()
  2. ->where(['need_review' => true]);
  3.  
  4. $unpublished = $articles->find()
  5. ->where(['published' => false]);
  6.  
  7. $unpublished->unionAll($inReview);

Subqueries

Subqueries are a powerful feature in relational databases and building them inCakePHP is fairly intuitive. By composing queries together, you can makesubqueries:

  1. // Prior to 3.6.0 use association() instead.
  2. $matchingComment = $articles->getAssociation('Comments')->find()
  3. ->select(['article_id'])
  4. ->distinct()
  5. ->where(['comment LIKE' => '%CakePHP%']);
  6.  
  7. $query = $articles->find()
  8. ->where(['id IN' => $matchingComment]);

Subqueries are accepted anywhere a query expression can be used. For example, inthe select() and join() methods.

Adding Locking Statements

Most relational database vendors support taking out locks when doing selectoperations. You can use the epilog() method for this:

  1. // In MySQL
  2. $query->epilog('FOR UPDATE');

The epilog() method allows you to append raw SQL to the end of queries. Youshould never put raw user data into epilog().

Executing Complex Queries

While the query builder makes it easy to build most queries, very complexqueries can be tedious and complicated to build. You may want to executethe desired SQL directly.

Executing SQL directly allows you to fine tune the query that will be run.However, doing so doesn’t let you use contain or other higher level ORMfeatures.