Avoid N+1 Queries in CakePHP with contain() Eager Loading
Prevent N+1 queries in CakePHP by loading parent and associated records together with ORM contain().
28 Apr 2026, 04:24 UTC

The problem: one query becomes many
When a CakePHP controller fetches a list of parent records, such as articles, and the template accesses each article's author, the ORM can issue one query for the articles and then one additional query for every author. This is the N+1 query problem: the number of database queries grows with the number of rows, which slows page response and increases database load as data volume grows.
Useful takeaway
Call contain() on a query object to tell CakePHP to load parent entities and their associated records together. The ORM issues a single query with SQL joins, and the resulting entities already include nested association data so the template does not trigger extra queries.
Prerequisites
- A CakePHP 3.x or 4.x application. The
contain()behavior described here is consistent across both major versions. - A configured datasource in
config/app.php. - Table models with associations declared, such as
belongsToorhasMany. - A controller action that calls
Table::find()through the table locator or model property.
Declare the association
Before eager loading, the source table must know about the association. In this example, articles belong to an author and have many comments:
// src/Model/Table/ArticlesTable.php
namespace App\Model\Table;
use Cake\ORM\Table;
class ArticlesTable extends Table
{
public function initialize(array $config): void
{
parent::initialize($config);
$this->belongsTo('Authors', [
'foreignKey' => 'author_id',
]);
$this->hasMany('Comments', [
'foreignKey' => 'article_id',
]);
}
}
Place this code in the application model layer. No shell command is required; the class file is loaded by the application autoloader.
Eager load associations in a controller
Add contain() to the finder in the controller action:
// src/Controller/ArticlesController.php
namespace App\Controller;
use Cake\ORM\TableRegistry;
class ArticlesController extends AppController
{
public function index()
{
$articlesTable = $this->fetchTable('Articles');
$query = $articlesTable
->find()
->contain(['Authors', 'Comments']);
$articles = $query->all();
$this->set(compact('articles'));
}
}
contain() accepts association names as strings. CakePHP builds SQL joins for belongsTo associations and handles hasMany associations according to the association configuration and database driver.
Load nested associations
Use dot notation to traverse deeper into the association graph. If authors have a related profile table:
$query = $articlesTable
->find()
->contain(['Authors.Profiles', 'Comments']);
This asks the ORM to load articles together with authors and each author's profile.
Limit the columns loaded inside contain()
Loading every column from every associated table wastes memory. Pass a closure to contain() to select only the fields the view needs:
$query = $articlesTable
->find()
->contain([
'Authors' => function ($query) {
return $query->select(['id', 'name', 'email']);
},
'Comments' => function ($query) {
return $query->select(['id', 'article_id', 'body', 'created']);
}
]);
The closure receives the association query object and should return it after applying select() or other conditions.
Eager loading is not for filtering parent rows
Use contain() only when you need to display associated data. It loads related records but does not remove parent rows that lack matches, and it does not filter parents by association criteria.
If you need to show only articles that have at least one comment, use matching() or innerJoinWith() instead:
// Articles that have comments; avoids duplicate parent rows from hasMany joins
$query = $articlesTable
->find()
->innerJoinWith('Comments');
Using contain() with multiple hasMany associations can produce a Cartesian product: one article with five comments and five tags can generate twenty-five combined rows. Limit contained associations to what the template actually renders.
Expected checks
- Enable DebugKit or query logging in your local environment.
- Request the controller action in a browser or through a test request.
- Open the SQL log panel and compare the query count before and after adding
contain(). - Confirm the log shows one joined query instead of repeated per-row
SELECTstatements for authors or comments. - Vary the number of articles in test data and assert that the executed query count does not increase proportionally.
- Inspect a returned entity in the template or debugger and confirm
$article->author->nameand$article->commentsare populated without additional database calls.
There is no rollback step because changing a finder query does not modify stored data. If the new query produces unexpected results, remove contain() or replace it with matching() or field-limited closures as described above.
Limitations and practical verification
contain()increases the width of the result set. Monitor memory usage when loading manyhasManyassociations.- Only eager load associations used in the current view. Unused contained data still consumes memory and query time.
- Syntax for middleware and PSR-7 differs between CakePHP 3.x and 4.x, but
contain()usage in table queries is stable across both versions. - Verify behavior in your own application with DebugKit enabled rather than assuming query counts from documentation.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.