PHPackages                             kyzegs/doctrine-entity-preloader - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. kyzegs/doctrine-entity-preloader

ActiveLibrary[Database &amp; ORM](/categories/database)

kyzegs/doctrine-entity-preloader
================================

Efficient &amp; easy to use solution to n+1 problem in Doctrine ORM

03PHP

Since Jun 25Pushed 4w agoCompare

[ Source](https://github.com/Kyzegs/doctrine-entity-preloader)[ Packagist](https://packagist.org/packages/kyzegs/doctrine-entity-preloader)[ RSS](/packages/kyzegs-doctrine-entity-preloader/feed)WikiDiscussions master Synced 1w ago

READMEChangelogDependenciesVersions (1)Used By (0)

[![Doctrine Entity Preloader banner](banner.svg)](banner.svg)

Doctrine Entity Preloader
=========================

[](#doctrine-entity-preloader)

`kyzegs/doctrine-entity-preloader` is a PHP library designed to tackle the n+1 query problem in Doctrine ORM by efficiently preloading related entities. This library offers a flexible and powerful way to optimize database access patterns, especially in cases with complex entity relationships.

- 🚀 **Performance Boost:** Minimizes n+1 issues by preloading related entities with **constant number of queries**.
- 🔄 **Flexible:** Supports all associations: `#[OneToOne]`, `#[OneToMany]`, `#[ManyToOne]`, and `#[ManyToMany]`.
- 💡 **Easy Integration:** Simple to integrate with your existing Doctrine setup (supports both v2 and v3).

Comparison
----------

[](#comparison)

[Default](https://docs.google.com/presentation/d/1sSlZOxmEUVKt0l8zhimex-6lR0ilC001GXh8colaXxg/edit#slide=id.g30998e74a82_0_0)[Manual](https://docs.google.com/presentation/d/1sSlZOxmEUVKt0l8zhimex-6lR0ilC001GXh8colaXxg/edit#slide=id.g309b68062f4_0_0)[Fetch Join](https://docs.google.com/presentation/d/1sSlZOxmEUVKt0l8zhimex-6lR0ilC001GXh8colaXxg/edit#slide=id.g309b68062f4_0_15)[setFetchMode](https://docs.google.com/presentation/d/1sSlZOxmEUVKt0l8zhimex-6lR0ilC001GXh8colaXxg/edit#slide=id.g309b68062f4_0_35)[**EntityPreloader**](https://docs.google.com/presentation/d/1sSlZOxmEUVKt0l8zhimex-6lR0ilC001GXh8colaXxg/edit#slide=id.g309b68062f4_0_265)[OneToMany](tests/EntityPreloadBlogOneHasManyTest.php)🔴 1 + n🟢 2🟠 1, but
duplicate rows🟢 2🟢 2[OneToManyDeep](tests/EntityPreloadBlogOneHasManyDeepTest.php)🔴 1 + n + n²🟢 3🟠 1, but
duplicate rows🔴 2 + n²🟢 3[OneToManyAbstract](tests/EntityPreloadBlogOneHasManyAbstractTest.php)🔴 1 + n + n²🟠 3, but
duplicate rows🟠 1, but
duplicate rows🔴 2 + n²🟠 3, but
duplicate rows[ManyToOne](tests/EntityPreloadBlogManyHasOneTest.php)🔴 1 + n🟢 2🟠 1, but
duplicate rows🟢 2🟢 2[ManyToOneDeep](tests/EntityPreloadBlogManyHasOneDeepTest.php)🔴 1 + n + n🟢 3🟠 1, but
duplicate rows🔴 2 + n🟢 3[ManyToMany](tests/EntityPreloadBlogManyHasManyTest.php)🔴 1 + n🟢 2🟠 1, but
duplicate rows🔴 1 + n🟢 2### Comparison vs. Manual Preload

[](#comparison-vs-manual-preload)

Unlike manual preload, the EntityPreloader does not require writing custom queries for each association.

### Comparison vs. Fetch Join

[](#comparison-vs-fetch-join)

Unlike fetch joins, the EntityPreloader does not fetches duplicate data, which slows down both the query and the hydration process, except when necessary to prevent additional queries fired by Doctrine during hydration process.

The fetch join scales poorly with the number of associations. With every preloaded association, the number of duplicate rows grows. The EntityPreloader does not have this problem.

### Comparison vs. setFetchMode

[](#comparison-vs-setfetchmode)

Unlike `Doctrine\ORM\AbstractQuery::setFetchMode` it can

- preload nested associations
- preload `#[ManyToMany]` association
- avoid additional queries fired by Doctrine during hydration process

Installation
------------

[](#installation)

To install the library, use Composer:

```
composer require kyzegs/doctrine-entity-preloader
```

### PHPStan

[](#phpstan)

This library provides PHPStan integration:

- **extension.neon** - Infers return types for `EntityPreloader::preload()` based on the preloaded association
- **rules.neon** - Validates that the property name passed to `preload()` exists on the entity

If you use [PHPStan](https://phpstan.org/) and have [phpstan/extension-installer](https://github.com/phpstan/extension-installer) installed, the extension and rules are enabled automatically.

Otherwise, add the following to your `phpstan.neon`:

```
includes:
    - vendor/kyzegs/doctrine-entity-preloader/extension.neon
    - vendor/kyzegs/doctrine-entity-preloader/rules.neon
```

If [phpstan/phpstan-doctrine](https://github.com/phpstan/phpstan-doctrine) is installed and `objectManagerLoader` is used, all mapping formats become available (xml, phpdoc, yaml). Otherwise, only modern attributes are supported.

Usage
-----

[](#usage)

Below is a basic example demonstrating how to use `EntityPreloader` to preload related entities and avoid the n+1 problem:

```
use Kyzegs\DoctrineEntityPreloader\EntityPreloader;

$categories = $entityManager->getRepository(Category::class)->findAll();

$preloader = new EntityPreloader($entityManager);
$articles = $preloader->preload($categories, 'articles'); // 1 query to preload articles
$preloader->preload($articles, 'tags'); // 2 queries to preload tags
$preloader->preload($articles, 'comments'); // 1 query to preload comments

// no more queries are needed now
foreach ($categories as $category) {
    foreach ($category->getArticles() as $article) {
        echo $article->getTitle(), "\n";

        foreach ($article->getTags() as $tag) {
            echo $tag->getLabel(), "\n";
        }

        foreach ($article->getComments() as $comment) {
            echo $comment->getText(), "\n";
        }
    }
}
```

Selective Preloading and Partial Collections
--------------------------------------------

[](#selective-preloading-and-partial-collections)

`EntityPreloader` can preload filtered relations into Doctrine association itself without rewriting root query and without root fetch joins. This avoids duplicated root rows and keeps root pagination safe.

Simple preload stays unchanged:

```
$entityPreloader->preload($orders, [
    'customer',
    'items',
]);
```

Selective preload with Doctrine `Criteria`:

```
use Doctrine\Common\Collections\Criteria;
use Kyzegs\DoctrineEntityPreloader\Preload;

$entityPreloader->preload($merchants, [
    'transactions' => Preload::criteria(
        Criteria::create()
            ->where(Criteria::expr()->eq('status', TransactionStatus::Paid))
            ->orderBy(['createdAt' => Criteria::DESC])
    ),
]);

foreach ($merchants as $merchant) {
    $paidTransactions = $merchant->getTransactions(); // initialized
}
```

Advanced query customization with `PreloadQueryBuilder`:

```
use Kyzegs\DoctrineEntityPreloader\Preload;
use Kyzegs\DoctrineEntityPreloader\PreloadQueryBuilder;

$entityPreloader->preload($merchants, [
    'transactions' => Preload::query(
        static function (PreloadQueryBuilder $query): void {
            $query
                ->join('entity.paymentMethod', 'paymentMethod')
                ->andWhere('paymentMethod.code IN (:codes)')
                ->setParameter('codes', ['ideal', 'bancontact'])
                ->addOrderBy('entity.createdAt', 'DESC');
        }
    ),
]);
```

Nested customized preload:

```
use Doctrine\Common\Collections\Criteria;
use Kyzegs\DoctrineEntityPreloader\Preload;

$entityPreloader->preload($articles, [
    'comments' => Preload::criteria(
        Criteria::create()
            ->where(Criteria::expr()->eq('approved', true))
    )->preload([
        'author',
    ]),
]);
```

### Warning: Partial Collections

[](#warning-partial-collections)

Selective preloading initializes a partial Doctrine collection. Collection is considered loaded, but can contain only rows matching preload criteria. This is similar to conditional fetch join behavior. Do not use selective mode in code paths expecting full association content.

Additional rules:

- Dirty collections are rejected with `DirtyCollectionException`.
- Already initialized collections are rejected by default for selective preload. Use `replaceInitializedCollection()` explicitly if overwrite is intended.
- `Criteria::setMaxResults()` is rejected for to-many selective preloads because it is global child limit, not per-parent limit.
- Root query stays unchanged; relation rows are loaded in separate preload query.

Configuration
-------------

[](#configuration)

`EntityPreloader` allows you to adjust batch sizes and fetch join limits to fit your application's performance needs:

- **Batch Size:** Set a custom batch size for preloading to optimize memory usage.
- **Max Fetch Join Same Field Count:** Define the maximum number of join fetches allowed per field.

```
$preloader->preload(
    $articles,
    'category',
    batchSize: 20,
    maxFetchJoinSameFieldCount: 5
);
```

### Doctrine ORM filters (e.g. softdeleteable)

[](#doctrine-orm-filters-eg-softdeleteable)

Doctrine ORM SQL filters are applied to preload queries the same way they are applied to repository queries. This is separate from `Criteria`-based selective preloading:

- `Criteria` adds explicit conditions to selective preload query.
- ORM filters are global SQL filters handled by Doctrine (`$entityManager->getFilters()`).

Global default preload filter policy:

```
use Kyzegs\DoctrineEntityPreloader\EntityPreloader;
use Kyzegs\DoctrineEntityPreloader\PreloadFilterPolicy;

$preloader = new EntityPreloader(
    $entityManager,
    PreloadFilterPolicy::create()->withoutFilters('softdeleteable'),
);
```

Per-association override:

```
use Kyzegs\DoctrineEntityPreloader\Preload;
use Kyzegs\DoctrineEntityPreloader\PreloadFilterPolicy;

$preloader = new EntityPreloader(
    $entityManager,
    PreloadFilterPolicy::create()->withoutFilters('softdeleteable'),
);

$preloader->preload($categories, [
    'articles' => Preload::association()->enableFilters('softdeleteable'),
]);
```

Temporarily set filter parameters for one preload:

```
use Kyzegs\DoctrineEntityPreloader\Preload;

$preloader->preload($categories, [
    'articles' => Preload::association()
        ->enableFilters('softdeleteable')
        ->withFilterParameter('softdeleteable', 'deletedValue', 0),
]);
```

Factory helpers are also available:

```
Preload::enableFilters('softdeleteable');
Preload::withoutFilters('softdeleteable');
Preload::withFilterParameter('softdeleteable', 'deletedValue', 0);
```

Limitations
-----------

[](#limitations)

- no support for indexed collections
- no support for dirty collections
- no support for composite primary keys

###  Health Score

21

—

LowBetter than 17% of packages

Maintenance61

Regular maintenance activity

Popularity3

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity11

Early-stage or recently created project

 Bus Factor1

Top contributor holds 61.1% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://www.gravatar.com/avatar/eb13f61de13b186245a047cd1d882784e4dacb5b9f2a8f930b20e5992159e61a?d=identicon)[Kyzegs](/maintainers/Kyzegs)

---

Top Contributors

[![JanTvrdik](https://avatars.githubusercontent.com/u/175109?v=4)](https://github.com/JanTvrdik "JanTvrdik (22 commits)")[![janedbal](https://avatars.githubusercontent.com/u/1993453?v=4)](https://github.com/janedbal "janedbal (11 commits)")[![Kyzegs](https://avatars.githubusercontent.com/u/45851377?v=4)](https://github.com/Kyzegs "Kyzegs (3 commits)")

---

Tags

doctrinedoctrine-ormsymfony

### Embed Badge

![Health badge](/badges/kyzegs-doctrine-entity-preloader/health.svg)

```
[![Health](https://phpackages.com/badges/kyzegs-doctrine-entity-preloader/health.svg)](https://phpackages.com/packages/kyzegs-doctrine-entity-preloader)
```

###  Alternatives

[jdorn/sql-formatter

a PHP SQL highlighting library

3.9k117.2M118](/packages/jdorn-sql-formatter)[propel/propel1

Propel is an open-source Object-Relational Mapping (ORM) for PHP5.

8351.6M87](/packages/propel-propel1)[jfelder/oracledb

Oracle DB driver for Laravel

11518.4k](/packages/jfelder-oracledb)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
