cphalcon icon indicating copy to clipboard operation
cphalcon copied to clipboard

[BUG]: Eager Loader does not batch a nested eager path when the first segment is a hasMany relation

Open Alistar84 opened this issue 3 months ago • 4 comments

Describe the bug Phalcon\Mvc\Model\Eager\Loader (native eager loader, Model::find()/findFirst(['eager' => [...]])) does not batch a nested path when the first segment of that path is a hasMany relation. It silently falls back to one query per parent row for the nested relation instead of a single batched WHERE id IN (...) - no error, correct data, but no eager-loading benefit at all for that level.

This contradicts the documented behavior of Phalcon\Mvc\Model\Eager\PathTree, whose own docblock states:

"The number of queries an eager load costs follows the number of nodes in this tree, not the number of elements supplied."

In the reproduction below, Author::findFirst(['eager' => ['Books.Publisher']]) fires one query per Book for Publisher (4 books → 4 queries) instead of a single WHERE id IN (...) batch query - even though Books.Publisher is only 2 nodes deep.

Calling Eager\Loader::loadResultset() directly on the already-fetched Books collection (with a path relative to Book, i.e. ['Publisher']) does batch correctly. So the batching logic itself works - it's specifically not being applied to nested segments below a hasMany boundary when going through find()/findFirst()'s own 'eager' option.

To Reproduce

Schema (MySQL):

CREATE TABLE authors (id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(50));
CREATE TABLE publishers (id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(50));
CREATE TABLE books (id INT PRIMARY KEY AUTO_INCREMENT, author_id INT, publisher_id INT, title VARCHAR(50));
INSERT INTO authors (name) VALUES ('Author 1');
INSERT INTO publishers (name) VALUES ('Publisher A'),('Publisher B'),('Publisher C'),('Publisher D');
INSERT INTO books (author_id, publisher_id, title) VALUES (1,1,'Book 1'),(1,2,'Book 2'),(1,3,'Book 3'),(1,4,'Book 4');

Script (repro.php):

<?php
use Phalcon\Di\FactoryDefault;
use Phalcon\Db\Adapter\Pdo\Mysql;
use Phalcon\Mvc\Model;
use Phalcon\Mvc\Model\Manager;
use Phalcon\Mvc\Model\MetaData\Memory as MetaDataMemory;
use Phalcon\Cache\AdapterFactory;
use Phalcon\Storage\SerializerFactory;
use Phalcon\Cache\Cache;
use Phalcon\Events\Manager as EventsManager;
use Phalcon\Mvc\Model\Eager\Loader as EagerLoader;

require __DIR__ . '/vendor/autoload.php';

$dbConfig = ['host' => '127.0.0.1', 'username' => 'root', 'password' => '', 'dbname' => 'eager_repro', 'charset' => 'utf8mb4'];

$di = new FactoryDefault();
$di->setShared('modelsManager', fn () => new Manager());
$di->setShared('modelsMetadata', fn () => new MetaDataMemory());
$di->setShared('modelsCache', function () {
    $adapterFactory = new AdapterFactory(new SerializerFactory());
    return new Cache($adapterFactory->newInstance('memory'));
});

$queryCount = 0;
$eventsManager = new EventsManager();
$eventsManager->attach('db:afterQuery', function ($event, $connection) use (&$queryCount) {
    if (stripos($connection->getSQLStatement(), 'INFORMATION_SCHEMA') === false) $queryCount++;
});
$di->setShared('db', function () use ($dbConfig, $eventsManager) {
    $conn = new Mysql($dbConfig);
    $conn->setEventsManager($eventsManager);
    return $conn;
});

class Author extends Model {
    public $id; public $name;
    public function initialize() {
        $this->setSource('authors');
        $this->hasMany('id', Book::class, 'author_id', ['alias' => 'Books']);
    }
}
class Book extends Model {
    public $id; public $author_id; public $publisher_id; public $title;
    public function initialize() {
        $this->setSource('books');
        $this->belongsTo('author_id', Author::class, 'id', ['alias' => 'Author']);
        $this->belongsTo('publisher_id', Publisher::class, 'id', ['alias' => 'Publisher']);
    }
}
class Publisher extends Model {
    public $id; public $name;
    public function initialize() { $this->setSource('publishers'); }
}

// Bug: nested path through a hasMany does not batch.
$queryCount = 0;
$author = Author::findFirst(['eager' => ['Books.Publisher']]);
foreach ($author->Books as $book) { echo $book->Publisher->name . PHP_EOL; }
echo "\nQueries fired: {$queryCount} (expected 3, got 6 - one per book instead of one batched IN())\n";

// Control: loadResultset() directly on the collection DOES batch correctly.
$queryCount = 0;
$author2 = Author::findFirst(['eager' => ['Books']]);
$eagerLoader = new EagerLoader($di->getShared('modelsManager'));
$eagerLoader->loadResultset($author2->Books, Book::class, \Phalcon\Mvc\Model\Eager\PathTree::parse(['Publisher']));
foreach ($author2->Books as $book) { echo $book->Publisher->name . PHP_EOL; }
echo "\nQueries fired (control): {$queryCount} (correctly batched)\n";

Expected behavior

Queries fired: 3 (1 author + 1 books + 1 publishers WHERE id IN (...))

Actual behavior

Queries fired: 6 (1 author + 1 books + 4 separate single-row publisher lookups)

The control block (using loadResultset() directly on the collection) correctly produces 3 queries, confirming the batching logic itself is sound - it's just not applied to nested paths under a find()/findFirst()'s 'eager' key when the ancestor segment is hasMany.

Impact

This is a silent performance regression, not a crash: data comes back correct, so the classic N+1 pattern is easy to miss in review and only shows up under load or when watching real query counts. Any application eager-loading a nested belongsTo/hasOne chain below a hasMany collection (a very common pattern - e.g. "load all orders for a customer, with each order's product") gets zero benefit from the native eager loader at that level despite no error being raised.

Workaround

Call Eager\Loader::loadResultset() directly on the already-fetched collection, with a path relative to it, instead of relying on find()'s own 'eager' option for anything nested below a hasMany.

Details

  • Phalcon version: 5.20.3
  • PHP Version: 8.4
  • Server: Nginx
  • Database: MySQL

Alistar84 avatar Aug 27 '26 14:08 Alistar84

@Alistar84 AFAIK findFirst never runs the eager route, find does. If you don't mind can you run the same thing but use something like

...::find(.... 'limit' => 1, 'eager' => ['Books'])

and see what the query count offers? That would either solidify this as a bug or change it to a NFR.

niden avatar Aug 27 '26 16:08 niden

You're right, and it changes the diagnosis. I ran the exact same repro three ways (same data: 1 author, 4 books, 4 distinct publishers; query count excludes metadata/introspection queries):

// 1. findFirst() with nested eager
$author = Author::findFirst(['eager' => ['Books.Publisher']]);
// -> 6 queries (1 author + 1 books + 4 separate publisher lookups)

// 2. find() with limit(1) and the same nested eager
$result = Author::find(['limit' => 1, 'eager' => ['Books.Publisher']]);
// -> 3 queries (1 author + 1 books + 1 batched publishers WHERE id IN (...))

// 3. find() with multiple authors (no limit), same nested eager
$authors = Author::find(['eager' => ['Books.Publisher']]);
// -> 3 queries total across all authors (correctly batched)

So find() batches the nested path correctly in every case I tried, including limit(1) and multi-row. Only findFirst() fails to batch — it falls back to one query per row for the nested relation, silently, with correct data.

Given find(['limit' => 1, ...]) and findFirst(...) are meant to be semantically equivalent (return the first matching record), I'd still call this a bug rather than an NFR: findFirst() should get the same eager-loading behavior find() already has, since they're documented as the same operation with a different return shape. Happy to narrow the title/scope of the issue to "findFirst() doesn't take the eager route that find() uses for nested paths" if that's clearer for triage.

Alistar84 avatar Aug 31 '26 08:08 Alistar84

Thanks. I will see what I can do.

niden avatar Aug 31 '26 18:08 niden

Resolved in https://github.com/phalcon/cphalcon/pull/17551

niden avatar Sep 02 '26 20:09 niden