There's a scene I see in almost every CakePHP project I review. The app works perfectly in development: twenty test rows, instant responses, everything clean. Then production arrives, the table grows, and suddenly a page that "worked" takes eight seconds to load.
The culprit is almost never the database. It's the application. It's a silent, extremely common pattern called N+1, and the good news is that CakePHP ships the tools to eliminate it entirely: contain() to load associations and matching() or innerJoinWith() to filter by them.
This article is a visual and practical guide to understanding the N+1 problem, detecting it with real data, and fixing it by using the ORM the way it was designed — without writing raw SQL.
What Is the N+1 Problem?
N+1 happens when we fetch the main list with one query and then resolve each related item with one more query. With N items, we end up running N+1 queries.
CakePHP does not load associations automatically: if you don't ask for them with contain(), they aren't there. That's why N+1 usually shows up when we resolve each association inside a loop instead of loading it all at once:
// ArticlesController::index()
$articles = $this->Articles->find()->all(); // 1 query
$authorsTable = $this->fetchTable('Authors');
foreach ($articles as $article) {
$author = $authorsTable->get($article->author_id); // 1 query per article!
echo $author->name;
}
The code looks fine and "works." But with 100 articles you just ran 101 queries.
The Disaster Diagram
1 query -> SELECT * FROM articles
N queries -> SELECT * FROM authors WHERE id = ? (one per article)
Total: 1 + N = 101 queries
And you don't have to write the loop by hand: the same N+1 slips in when the per-row query is hidden inside a helper, an element, a cell, or an accessor that runs for every record in the template.
The dangerous part is that the cost grows linearly with your data. You won't notice it with 20 rows. With 2,000 rows, that's 2,001 round trips to the database: the page doesn't just get slower, it can time out under load. And the symptom usually shows up late, already in production.
This same pattern hides behind the worst bottlenecks in listings, dashboards, feeds, and APIs.
How to Detect It Before It Reaches Production
You can't fix what you can't measure. Before optimizing, you need to see the N+1 with your own eyes.
Option 1: DebugKit (the Fastest)
If you have DebugKit installed (and in development you should), every page shows an SQL panel. There you'll see the full list of queries for that request. If you find dozens of identical queries changing only the WHERE id = ?, you've got it.
Option 2: The Query Log
To inspect the SQL a single query generates, use debug() or sql():
// Shows the SQL and bound parameters, without running the results
debug($query);
// Shows the final rendered SQL (requires DebugKit installed)
sql($query);
Option 3: Count Queries in a Test
The most robust way to protect a page against regressions is to measure it in a test. You can count the queries executed and set a maximum budget:
use Cake\Log\Engine\ArrayLog;
use Cake\Log\Log;
public function testIndexDoesNotTriggerNPlusOne(): void
{
// Requires query logging enabled on the connection ('log' => true)
$logger = new ArrayLog(['scopes' => ['queriesLog']]);
Log::setConfig('queries', $logger);
$this->get('/articles/index');
$queries = $logger->read();
$this->assertNotEmpty($queries, 'Query logging is not enabled');
$this->assertLessThanOrEqual(3, count($queries), 'N+1 was triggered!');
}
The logger replacement is global to the process, so restore your app's queries logger in tearDown() to keep other tests isolated. Also warm the schema before counting; otherwise reflection queries can inflate the budget. Pair the budget with an assertion on the number of results: counting queries will not catch duplicate parent rows.
Rule of thumb: every time you see a loop that resolves an association with a query, assume there's an N+1 until you prove otherwise.
The Fix: Eager Loading with contain()
CakePHP, by default, does not load any associations when you call find(). You have to explicitly tell it which ones you want, and that's eager loading. The instruction is contain():
// ArticlesController::index()
$articles = $this->Articles->find()
->contain(['Authors'])
->all();
Since Articles belongsTo Authors is a many-to-one relationship, CakePHP resolves it with a JOIN, so the whole listing comes back in a single query:
1 query -> SELECT * FROM articles LEFT JOIN authors ON articles.author_id = authors.id
We go from 101 queries to 1, no matter how many articles there are.
Why Is It So Efficient?
CakePHP picks the most efficient strategy based on the type of association:
| Association type | Default strategy | Queries |
|---|---|---|
belongsTo (N:1) / hasOne (1:1) |
join |
1: a JOIN inside the main query |
hasMany (1:N) / belongsToMany (N:N) |
subquery (5.4+) |
2: the main query + a second query |
For belongsTo/hasOne, the JOIN brings the association in the same query. For hasMany/belongsToMany, a JOIN would duplicate the parent's rows, so CakePHP runs a second query that fetches all children at once:
1 query -> SELECT * FROM articles
1 query -> SELECT * FROM comments WHERE article_id IN (SELECT id FROM articles)
Since CakePHP 5.4 that second query uses the subquery strategy by default; before that it used select, which generated IN (1, 2, 3, ...). Either way, the total is a fixed number of queries (1 or 2), no matter how many records there are. You can check the default strategy for each association type in the CakePHP Associations documentation.
Nested Contain
You can load associations as deep as you need using dot notation or nested arrays:
$articles = $this->Articles->find()
->contain([
'Authors.Addresses',
'Comments.Authors',
])
->all();
Contain with Conditions and Specific Fields
contain() accepts a closure to filter and narrow what gets loaded. The closure receives a Cake\ORM\Query\SelectQuery object (add use Cake\ORM\Query\SelectQuery; to your controller). It's the right way to fetch only what the view needs:
$articles = $this->Articles->find()
->contain(['Comments' => function (SelectQuery $q) {
return $q
->select(['id', 'article_id', 'body', 'created'])
->where(['Comments.approved' => true]);
}])
->all();
When using
select()withcontain(): remember to include the foreign key (article_idin the example). It's the column the ORM uses to match child records with their parent.
contain() and matching(): Not the Same Thing
This is where most people get confused. Both load or filter associated data, but they solve different problems:
contain()loads associated data, but does not restrict the parent records. It brings every article and attaches its comments (filtered or not).matching()restricts the parent records based on their associations. It brings only the articles that satisfy a condition on their associations.
Think of it this way:
- Do I want an article with its comments? →
contain() - Do I want only the articles that have a certain comment? →
matching()
The Case That Makes It Click
Let's say we want to list articles. Look at the two queries and what they return:
// THIS returns ALL the articles.
// Each one gets only its approved comments loaded (may be empty).
$articles = $this->Articles->find()
->contain(['Comments' => function (SelectQuery $q) {
return $q->where(['Comments.approved' => true]);
}])
->all();
// THIS returns ONLY the articles that have at least one approved comment.
$articles = $this->Articles->find()
->matching('Comments', function (SelectQuery $q) {
return $q->where(['Comments.approved' => true]);
})
->distinct(['Articles.id'])
->all();
The difference is huge. In the first case, an article with no approved comments still shows up, just with an empty comments array. In the second, that article disappears.
matching() Uses an INNER JOIN (Which Is Why You May Need distinct())
Internally, matching() builds an INNER JOIN against the associated table. That means if the same article has three approved comments, it will appear three times in the result. Plain ->distinct() by itself does not fix this: matching() also selects the association's columns so it can populate _matchingData, and DISTINCT over all of those columns still returns one row per comment. Use ->distinct(['Articles.id']), as the CakePHP documentation shows, or use innerJoinWith() if you don't need _matchingData.
| Feature | contain() |
matching() |
|---|---|---|
| Purpose | Load associated data | Filter by associated data |
| Restricts the parents? | No | Yes |
| Internal implementation | JOIN (belongsTo/hasOne) or a second query (hasMany/belongsToMany) | INNER JOIN (may need distinct(['Articles.id'])) |
| How to access the data | Via the $article->comments property |
Via $article->_matchingData |
| Result when no match | The parent still appears | The parent is excluded |
MySQL note:
distinct(['Articles.id'])compiles toGROUP BY Articles.idon MySQL and SQLite. On MySQL 5.7+ withONLY_FULL_GROUP_BY, it can fail ifmatching()still selects columns from the associated table. In that case, select only the parent fields, useinnerJoinWith(), or filter with a subquery/EXISTS.
innerJoinWith(): When You Only Need to Filter, Not Load
If you want the effect of matching() (filtering the parents) but don't need the association data in the result, use innerJoinWith(). It makes the same INNER JOIN, but doesn't hydrate the associated records, so it's lighter:
$articles = $this->Articles->find()
->innerJoinWith('Comments', function (SelectQuery $q) {
return $q->where(['Comments.approved' => true]);
})
->distinct()
->all();
Because innerJoinWith() does not add the association's fields to the select list, a plain distinct() works here.
Combining Both: Filter and Load
innerJoinWith() and contain() are not mutually exclusive. You can filter the articles with innerJoinWith() and load their approved comments with contain() in the same query:
$articles = $this->Articles->find()
->innerJoinWith('Comments', function (SelectQuery $q) {
return $q->where(['Comments.approved' => true]);
})
->contain(['Authors', 'Comments' => function (SelectQuery $q) {
return $q->where(['Comments.approved' => true]);
}])
->distinct()
->all();
innerJoinWith() restricts the articles without hydrating the matched rows, and contain() loads the approved comments as full entities. If you specifically need the matched comment through _matchingData, use matching() with distinct(['Articles.id']) instead.
Common Mistakes (and How to Avoid Them)
After reviewing many projects, these are the most common patterns. All of them are easy to fix once you recognize them.
- Loading more than the view uses.
contain()brings data, and bringing data costs. If the view only shows the author's name, don't contain their full profile, their addresses, and their session history. Contain only what's necessary:
// Bad: overloads the query with data nobody uses
$articles = $this->Articles->find()->contain(['Authors.Profiles.Addresses'])->all();
// Better: only what the view actually renders
$articles = $this->Articles->find()
->contain(['Authors' => function (SelectQuery $q) {
return $q->select(['id', 'name']);
}])
->all();
- Forgetting the foreign key when using
select(). If you callselect()on a contained association, always include the foreign key. It's the column the ORM needs to match child records with their parent, so it's worth checking every time you limit fields. - Using
limit()insidecontain()on ahasMany.limit()applies to the whole set of associated rows, not per parent, so it will not give you "the last 5 comments of each article." For a per-parent limit you need a different approach, such as a window function. Verify the generated SQL before relying on it. - Assuming
contain()filters the parents. It's the most common conceptual mistake, and we already covered it in thecontain()andmatching()section:contain()with conditions does not remove articles that have no matches. That's whatmatching()is for. - Hydrating entities when you only need a listing. For large read-only datasets (selects, reports, exports), building full entities is a waste. If you're not going to modify or save the data, skip hydration:
// For a <select>: you don't need entities, just key/value pairs
$authorsList = $this->Articles->Authors->find('list')->toArray();
// For large read-only datasets (CakePHP 5.4+)
$rows = $this->Articles->unhydratedFind()->all();
Hydration has a real CPU and memory cost per row, and on large listings skipping it can significantly reduce CPU time and memory use. See Getting Arrays Instead of Entities in the CakePHP docs.
Cheat Sheet: Which Tool Do I Use?
When in doubt, start with the question: do I need the associated data, or do I only need to filter by it?
| I need to... | Use |
|---|---|
| Load associated data (show the author, the comments) | contain() |
| Load associated data with conditions or specific fields | contain() + closure |
| Filter the parents by a condition on their association | matching() |
| Filter the parents without loading the associated data | innerJoinWith() |
| Filter and also load associated data | innerJoinWith() + contain() |
| Filter by a condition defined on the association | matching() |
Verification: How to Confirm the Fix Works
Don't close the fix without measuring before and after. Same dataset, same page, two numbers:
- Before: keep the original
find()and open the DebugKit SQL panel (or the counting test). Note the number of queries. With 100 articles you'll see something like101. - After: add
->contain(['Authors'])and measure again. You should see1for the listing itself (abelongsTois resolved with aJOIN; if you contain a 1:N association likeComments, you'll see2). - Validate the
matching()scenario: create an article with no approved comments. Confirm that withcontain()it still shows up, and that withmatching()it disappears. Then create an article with three approved comments and confirm thatmatching()+distinct(['Articles.id'])returns it once. That's how you check you picked the right tool.
A query-budget test, like the counting test we showed earlier, is the best investment: it turns this verification into something permanent and prevents a future change from reintroducing the N+1.
Conclusion
The N+1 problem isn't a framework bug; it's a pattern that emerges from using the ORM intuitively. The fix is just as natural once you understand the mental model:
contain()to load associations up front and cut N+1 down to a fixed number of queries (1 with aJOINfor belongsTo/hasOne; 2 for hasMany/belongsToMany).matching()to filter the parent records by their associations, addingdistinct(['Articles.id'])when the association can match multiple rows.innerJoinWith()when you only need the constraint, not the data.
The personal rule I apply is simple: every time I see a loop that resolves an association with a query, I stop the review and measure. If the view needs related data, it gets contained in the query; it doesn't get queried "by accident" inside the foreach. And if the page filters by a relation, it filters in the database, not in PHP after fetching everything.
That small change of habit is the difference between an app that scales and one that falls over the first time the table really grows.
Need help with this in your own CakePHP app?
Talk to a CakePHP expertGet the CakeDC newsletter
One email a month: releases, security advisories and one article worth reading.