CakePHP ORM: Custom Finders, Association Strategies, and Eager Loading to Eliminate N+1 Queries
Learn to design custom finder methods, choose eager loading strategies, and avoid N+1 queries in CakePHP 4.x/5.x with practical examples.
31 Dec 2025, 00:52 UTC

The N+1 Problem in a Typical Article List
When a page shows a list of articles and each article’s comment count, the code often looks like:
foreach ($articles as $article) {
echo $article->comments->count;
}
In development with ten rows the page loads instantly. In production with five hundred rows the response can take many seconds because the framework issues one query for the articles and then one additional query for each article’s comments – a classic N+1 pattern.
Custom Finder Methods Keep Controllers Thin
CakePHP’s ORM separates repository logic (the Table class) from domain objects (the Entity class). A custom finder lives in the Table and returns a Query object, allowing you to reuse the same logic in controllers, shells, or tests.
// src/Model/Table/ArticlesTable.php
namespace App\Model\Table;
use Cake\ORM\Query;
use Cake\ORM\Table;
class ArticlesTable extends Table {
public function initialize(array $config): void {
$this->hasMany('Comments', [
'className' => 'Comments',
'foreignKey' => 'article_id',
'strategy' => 'select', // default
]);
}
public function findPublished(Query $query, array $options = []): Query {
return $query->where(['Articles.published' => true])
->order(['Articles.created' => 'DESC']);
}
public function findRecent(Query $query, array $options = []): Query {
$days = $options['days'] ?? 30;
return $query->where([
'Articles.created >=' => new \\DateTime(\"-{$days} days\")
]);
}
}
In a controller you can chain finders without materializing data:
$articles = $this->Articles
->find('published')
->find('recent', ['days' => 7])
->all();
Association Loading Strategies: Select vs Subquery
The strategy option on hasMany and belongsToMany determines how contain() fetches related rows.
- select (default): CakePHP runs a second query with
WHERE article_id IN (…). Two queries total regardless of parent count, and the parent rows stay narrow, which is usually the fastest option. - subquery: The related data is added to the main query as a correlated subquery or join. Use this when you need to filter or order parents based on aggregated child data (e.g., “articles with at least three approved comments”).
For a simple article‑comment list, keep strategy => 'select'. Switch to subquery only when the parent query must incorporate child conditions in the same statement.
Worked Example: Eager Loading with Filtered Children
Requirement: Show published articles from the last 30 days, each with its approved comments only, ordered by newest comment first.
// Controller action
public function index()
{
$query = $this->Articles
->find('published')
->find('recent', ['days' => 30])
->contain(['Comments' => function ($q) {
return $q->where(['Comments.approved' => true])
->order(['Comments.created' => 'DESC']);
}]);
$articles = $this->paginate($query);
$this->set(compact('articles'));
}
With config/app.php set 'log' => true for the default datasource. The SQL log then shows two statements:
SELECT * FROM articles
WHERE published = 1 AND created >= '2026-11-04'
ORDER BY created DESC
LIMIT 20 OFFSET 0;
SELECT * FROM comments
WHERE article_id IN (1,2,3,…) AND approved = 1
ORDER BY created DESC;
No N+1 queries; the paginator respects the contain clause while applying its own limit/offset.
Trade‑off: Cartesian Product Risk
If you enable a join strategy for one association while keeping another as hasMany, the number of rows can explode. For example, contain(['Comments', 'Tags']) with both associations using the default select strategy remains safe, but changing Comments to strategy => 'join' multiplies article rows by the number of comments, and adding Tags multiplies again. The resulting Cartesian product can overwhelm the database.
Mitigation: keep hasMany associations on select (or subquery) for eager loading, and use matching() only when you need to filter the parent by the existence of a child (e.g., “articles that have at least one approved comment”). Avoid stacking multiple matching() calls on different hasMany associations.
Verification Checklist
- Enable SQL logging in
config/app.php:'Datasources' => ['default' => ['log' => true]]. - Load the page with
?debug_queries=1or inspectlogs/debug.log. You should see exactly two queries for a singlehasManywithcontain. - Add a second
hasManyand confirm the query count stays at three, not N+2. - Run an integration test with
IntegrationTestTraitthat asserts$this->assertResponseOk()and checkscount($this->viewVariable('articles'))matches the pagination limit.
Actionable Next Step
Pick a controller method that loads a list with related data. Wrap its base query in a custom finder, add a contain() closure that applies any child filters, and verify that the query count drops to two. This single change eliminates a whole class of performance regressions before they reach production.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.