Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
68d4831
Defer postLoad until the outermost hydration has finished
beberlei Nov 6, 2026
39f6f41
Fire deferred postLoad events when leaving the outermost hydration
beberlei Nov 6, 2026
ce34653
Initialize a lazy embeddable before reading its properties (#12707)
ker0x Nov 6, 2026
15b6b46
Document limitation of DateTime objects as identifiers
beberlei Nov 7, 2026
16d426f
Make SQLFilter example resolve the locale column from metadata
beberlei Nov 7, 2026
9ffe0f0
Handle null values in MySQL enum cookbook types
beberlei Nov 7, 2026
05f1387
Recommend the DBAL enum type and PHP enums in the MySQL enums cookbook
beberlei Nov 7, 2026
32d0eb0
Document mappedBy as required for OneToMany
beberlei Nov 7, 2026
2c39911
Fix misleading QueryBuilder IN() documentation
beberlei Nov 7, 2026
ae62701
Warn about timezone rule changes in the DateTime cookbook
beberlei Nov 7, 2026
028f4a3
Do not override datetimetz with UTCDateTimeType in the DateTime cookbook
beberlei Nov 7, 2026
530fc88
Clarify what privately owned means for orphanRemoval
beberlei Nov 7, 2026
36008ec
Document that replacing a collection with orphanRemoval deletes all p…
beberlei Nov 7, 2026
3c4eaeb
Document magic finders in a dedicated section
beberlei Nov 7, 2026
adf619f
Explain when repository methods use the identity map
beberlei Nov 7, 2026
c085af7
Update custom hydrator example to the current AbstractHydrator API
beberlei Nov 7, 2026
ef30bb1
Document how the initial value of a version field is set
beberlei Nov 7, 2026
77cc6bc
Remove outdated DBAL 2 SQL logger advice from batch processing docs
beberlei Nov 7, 2026
94ba74c
Document string literal quoting in DQL
beberlei Nov 7, 2026
13c55f5
Clarify orphanRemoval move order and limit replacement warning to one…
beberlei Nov 7, 2026
496a489
Mention caching when explaining that searches query the database
beberlei Nov 7, 2026
678c053
Merge pull request #12768 from beberlei/triaged-documentation-only-fixes
greg0ire Nov 7, 2026
9c37680
Merge pull request #12765 from beberlei/fix-nested-hydration-postload
greg0ire Nov 14, 2026
b34ffa8
Merge remote-tracking branch 'origin/3.7.x' into 3.8.x
greg0ire Nov 14, 2026
d52c15f
Migrate hydration test fixtures to the new hydrator API
greg0ire Nov 14, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions UPGRADE.md
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,43 @@ keep the previous behavior.

# Upgrade to 3.7

## `postLoad` is deferred until the outermost hydration has finished

Loading an entity can start further hydrations, for example for eagerly fetched
associations or inverse one-to-one associations. Each of these used to fire the
`postLoad` events of all entities hydrated so far, including entities that the
outer hydration was still working on. `postLoad` now fires once the outermost
hydration has finished, and the order of the events does not change.

This has the following consequences:

- Changes that a `postLoad` listener makes to a collection are no longer lost in
these cases. They are written to the database on the next flush, which includes
deleting entities from collections with `orphanRemoval`. Review listeners that
modify collections, as they may only have appeared to have no effect until now.
- Eagerly batch loaded collections no longer end up with duplicate items when a
`postLoad` listener accesses them.
- Code that runs during hydration, such as a custom hydrator or a custom DBAL type,
and loads an entity no longer sees the `postLoad` event of that entity fired when
the load returns. It fires at the end of the outermost hydration instead.
- If a `postLoad` listener throws an exception, the remaining events of that
hydration are not fired. This is not new, but more events can be affected,
because they are no longer fired in several steps.
- If the cleanup of a hydrator fails, `postLoad` events now fire right away instead
of with the next load.

`AbstractQuery::toIterable()` now fires `postLoad` at the end of each row, before the row
is yielded. Associations that are not part of the row are still not guaranteed to be
initialized.

- For `Query::toIterable()`, this used to happen while the row was being hydrated. Fetch
joined to-one associations are now set when `postLoad` fires.
- `NativeQuery::toIterable()` now behaves like `Query::toIterable()`, which it did not do
before. `postLoad` used to fire at the end of the iteration, unless a nested load fired
it earlier. Eager one-to-many collections used to be loaded in batches at the end of the
iteration, and got duplicate items when accessed during the iteration. They are now
loaded for each row, which causes one query per row and collection.

## Deprecated `Doctrine\ORM\Mapping\JoinColumns` attribute

Using it has no effect, it should have been removed in 3.0.0. Instead, use the
Expand Down
59 changes: 57 additions & 2 deletions docs/en/cookbook/mysql-enums.rst
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ By default Doctrine does not map the MySQL enum type to a Doctrine type.
This is because Enums contain state (their allowed values) and Doctrine
types don't.

This cookbook entry shows two possible solutions to work with MySQL enums.
This cookbook entry shows several possible solutions to work with MySQL enums.
But first a word of warning. The MySQL Enum type has considerable downsides:

- Adding new values requires to rebuild the whole table, which can take hours
Expand All @@ -23,6 +23,50 @@ But first a word of warning. The MySQL Enum type has considerable downsides:
settings. You can easily replicate the "allow only some values" requirement
in your Doctrine entities.

Recommended: PHP enums and the DBAL ``enum`` type
-------------------------------------------------

Since DBAL 4.2, the ``Doctrine\DBAL\Types\Types::ENUM`` type is available and
generates a native ``ENUM(...)`` column on MySQL and MariaDB (and a ``VARCHAR``
column on other platforms). Combined with :ref:`PHP backed enums
<reference-enum-mapping>`, the ORM fills in the allowed values from the enum
cases, converts between the database value and the enum instance and validates
the values for you:

.. code-block:: php

<?php
enum Visibility: string
{
case Visible = 'visible';
case Invisible = 'invisible';
}

#[Entity]
class Article
{
#[Column(type: Types::ENUM, enumType: Visibility::class)]
private Visibility $status;
}

Without a PHP enum, the allowed values can be passed with the ``values`` option:

.. code-block:: php

<?php
#[Entity]
class Article
{
#[Column(type: Types::ENUM, options: ['values' => ['visible', 'invisible']])]
private string $status;
}

If you do not need a native ``ENUM`` column, mapping a PHP backed enum to a
regular ``string`` column with ``enumType`` gives you the same type-safety while
avoiding the downsides listed above.

The following solutions are only needed when you cannot use DBAL 4.2 or newer.

Solution 1: Mapping to Varchars
-------------------------------

Expand Down Expand Up @@ -107,8 +151,12 @@ For example for the previous enum type:
return $value;
}

public function convertToDatabaseValue(mixed $value, AbstractPlatform $platform): string
public function convertToDatabaseValue(mixed $value, AbstractPlatform $platform): ?string
{
if ($value === null) {
return null;
}

if (!in_array($value, [self::STATUS_VISIBLE, self::STATUS_INVISIBLE], true)) {
throw new \InvalidArgumentException("Invalid status");
}
Expand Down Expand Up @@ -164,6 +212,10 @@ You can generalize this approach easily to create a base class for enums:

public function convertToDatabaseValue(mixed $value, AbstractPlatform $platform): mixed
{
if ($value === null) {
return null;
}

if (!in_array($value, $this->values, true)) {
throw new \InvalidArgumentException("Invalid '".$this->name."' value.");
}
Expand All @@ -177,6 +229,9 @@ You can generalize this approach easily to create a base class for enums:
}
}

The ``null`` checks allow the type to be used for nullable columns, since
Doctrine passes ``null`` to the type when the field has no value.

With this base class you can define an enum as easily as:

.. code-block:: php
Expand Down
24 changes: 23 additions & 1 deletion docs/en/cookbook/working-with-datetime.rst
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,13 @@ code before bootstrapping the ORM:
use DoctrineExtensions\DBAL\Types\UTCDateTimeType;

Type::overrideType('datetime', UTCDateTimeType::class);
Type::overrideType('datetimetz', UTCDateTimeType::class);

Do not override the ``datetimetz`` type with this class. ``UTCDateTimeType`` extends
``DateTimeType`` and uses its SQL declaration and format, while ``datetimetz`` columns
are declared with a timezone (for example ``TIMESTAMP(0) WITH TIME ZONE`` on PostgreSQL)
and use a format that includes the offset. Overriding it changes the generated schema
and breaks reading existing ``datetimetz`` values. If you need the same behavior for
``datetimetz`` columns, create a separate type that extends ``DateTimeTzType``.


To be able to transform these values
Expand Down Expand Up @@ -196,3 +202,19 @@ This snippet makes use of the fact that in-place modifications of a date object
are not detected by the change set computation: the UnitOfWork keeps the same
instance as the original value. This means we can modify the instance by setting
the previous local timezone without triggering an update.

.. warning::

Converting to UTC is only safe for points in time that are in the past or
near future, like the creation date of an event. The rules of a timezone (its
UTC offset and daylight saving time) are defined by the timezone database and can
change after the value was stored. When this happens, a UTC value that was
computed for a future local time, like a meeting at 10:00 in Europe/Berlin next
year, no longer corresponds to the intended local time when it is converted back.

For future local times, store the local date and time without conversion (for
example as a string or in a ``datetime`` column that is not converted to UTC)
together with the timezone name, and only compute the UTC value when it is needed.
See `Why not to convert a datetime to timestamp
<https://andreas.heigl.org/2016/12/22/why-not-to-convert-a-datetime-to-timestamp/>`_
for a longer explanation.
10 changes: 7 additions & 3 deletions docs/en/reference/attributes-reference.rst
Original file line number Diff line number Diff line change
Expand Up @@ -932,16 +932,20 @@ Required parameters:
- **targetEntity**: FQCN of the referenced target entity. Can be the
unqualified class name if both classes are in the same namespace.
*IMPORTANT:* No leading backslash!
- **mappedBy**: This option specifies the property name on the
targetEntity that is the owning side of this relation. A one-to-many
association is always the inverse side of a bidirectional association,
so this attribute is required. A unidirectional one-to-many association
is mapped with :ref:`#[ManyToMany] <attrref_manytomany>` and a unique join
column instead, see "One-To-Many, Unidirectional with Join Table" in
:doc:`association-mapping`.

Optional parameters:

- **cascade**: Cascade Option
- **orphanRemoval**: Boolean that specifies if orphans, inverse
OneToOne entities that are not connected to any owning instance,
should be removed by Doctrine. Defaults to false.
- **mappedBy**: This option specifies the property name on the
targetEntity that is the owning side of this relation. Its a
required attribute for the inverse side of a relationship.
- **fetch**: One of LAZY, EXTRA_LAZY or EAGER.
- **indexBy**: Index the collection by a field on the target entity.

Expand Down
13 changes: 4 additions & 9 deletions docs/en/reference/batch-processing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,14 @@ especially what the strategies presented here provide help with.

Having an SQL logger enabled when processing batches can have a
serious impact on performance and resource usage.
To avoid that, you should use a PSR logger implementation that can be
disabled at runtime.
SQL logging is configured with the ``Doctrine\DBAL\Logging\Middleware``,
which wraps the connection and cannot be removed from an existing
connection. To avoid the overhead, you should use a PSR logger
implementation that can be disabled at runtime.
For example, with Monolog, you can use ``Logger::pushHandler()``
to push a ``NullHandler`` to the logger instance, and then pop it
when you need to enable logging again.

With DBAL 2, you can disable the SQL logger like below:

.. code-block:: php

<?php
$em->getConnection()->getConfiguration()->setSQLLogger(null);

Bulk Inserts
------------

Expand Down
21 changes: 19 additions & 2 deletions docs/en/reference/dql-doctrine-query-language.rst
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,23 @@ are specified with ":name1", ":name2" and so on.
When referencing the parameters in ``Query#setParameter($param, $value)``
both named and positional parameters are used **without** their prefixes.

String Literals
~~~~~~~~~~~~~~~

String literals in DQL are enclosed in single quotes, for example
``'foo'``. A single quote inside a string literal is escaped by doubling
it: ``'bar''s house'``. Unlike some SQL dialects, DQL does not support
double quotes for string literals; ``"foo"`` results in a syntax error.

Prefer passing values as parameters instead of embedding them into the
query string, which also takes care of any quoting:

.. code-block:: php

<?php
$query = $em->createQuery('SELECT u FROM MyProject\Model\User u WHERE u.name = :name');
$query->setParameter('name', "bar's house");

DQL SELECT Examples
~~~~~~~~~~~~~~~~~~~

Expand Down Expand Up @@ -1245,9 +1262,9 @@ creating a class which extends ``AbstractHydrator``:

class CustomHydrator extends AbstractHydrator
{
protected function _hydrateAll()
protected function hydrateAllData(): array
{
return $this->_stmt->fetchAllAssociative();
return $this->stmt->fetchAllAssociative();
}
}

Expand Down
16 changes: 11 additions & 5 deletions docs/en/reference/events.rst
Original file line number Diff line number Diff line change
Expand Up @@ -710,13 +710,19 @@ postLoad
The postLoad event occurs after the entity has been loaded into the current
``EntityManager`` from the database or after ``refresh()`` has been applied to it.

The event is deferred until the outermost hydration has finished. Loading an entity
can start further hydrations, for example for eagerly fetched associations. Entities
hydrated that way receive their ``postLoad`` event at the end of the outermost hydration
as well, when all of their associations are populated.

.. warning::

When using ``Doctrine\ORM\AbstractQuery::toIterable()``, ``postLoad``
events will be executed immediately after objects are being hydrated, and therefore
associations are not guaranteed to be initialized. It is not safe to combine
usage of ``Doctrine\ORM\AbstractQuery::toIterable()`` and ``postLoad`` event
handlers.
When using ``Doctrine\ORM\AbstractQuery::toIterable()``, ``postLoad`` events are
executed after each row has been hydrated, and therefore associations that are
not part of that row are not guaranteed to be initialized. For example, eagerly
fetched to-one associations are only loaded at the end of the iteration. It is not
safe to rely on such associations in ``postLoad`` event handlers when using
``Doctrine\ORM\AbstractQuery::toIterable()``.

.. _reference-events-on-clear:

Expand Down
16 changes: 9 additions & 7 deletions docs/en/reference/filters.rst
Original file line number Diff line number Diff line change
Expand Up @@ -38,19 +38,21 @@ The ``SQLFilter#getParameter()`` function takes care of the proper quoting of pa

<?php
namespace Example;
use Doctrine\ORM\Mapping\ClassMetadata,
Doctrine\ORM\Query\Filter\SQLFilter;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Query\Filter\SQLFilter;

class MyLocaleFilter extends SQLFilter
{
public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias): string
public function addFilterConstraint(ClassMetadata $targetEntity, string $targetTableAlias): string
{
// Check if the entity implements the LocalAware interface
if (!$targetEntity->reflClass->implementsInterface('LocaleAware')) {
return "";
// Only filter entities that implement the LocaleAware interface and map a "locale" field
if (! $targetEntity->reflClass->implementsInterface(LocaleAware::class) || ! $targetEntity->hasField('locale')) {
return '';
}

return $targetTableAlias.'.locale = ' . $this->getParameter('locale'); // getParameter applies quoting automatically
// Resolve the column name from the metadata instead of assuming it,
// getParameter() applies quoting automatically
return $targetTableAlias . '.' . $targetEntity->getColumnName('locale') . ' = ' . $this->getParameter('locale');
}
}

Expand Down
14 changes: 14 additions & 0 deletions docs/en/reference/limitations-and-known-issues.rst
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,20 @@ will not be able to tell, since it does not have access to any metadata.
Thus, to avoid problems in this regard, it is best to avoid having multiple ``private`` fields of the
same name in class hierarchies containing entity and mapped superclasses.

Objects as identifier values
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The ``UnitOfWork`` builds the key of its identity map by casting the identifier
values to strings. Identifier values that are objects therefore only work when they
can be converted to a string, either because they implement ``Stringable`` or because
they are backed enums. Using a ``DateTime`` or ``DateTimeImmutable`` value as the
identifier, or as part of a composite identifier, fails with an
``Object of class DateTime could not be converted to string`` error.

Use a scalar column (for example the timestamp or a formatted date string) as the
identifier instead, or wrap the date in a custom value object that implements
``Stringable`` together with a custom DBAL type.

Known Issues
------------

Expand Down
5 changes: 3 additions & 2 deletions docs/en/reference/query-builder.rst
Original file line number Diff line number Diff line change
Expand Up @@ -490,8 +490,9 @@ complete list of supported helper methods available:
public function not($restriction); // Returns Expr\Func instance

// Example - $qb->expr()->in('u.id', array(1, 2, 3))
// Make sure that you do NOT use something similar to $qb->expr()->in('value', array('stringvalue')) as this will cause Doctrine to throw an Exception.
// Instead, use $qb->expr()->in('value', array('?1')) and bind your parameter to ?1 (see section above)
// Values in an array are quoted as literals, so $qb->expr()->in('u.name', array('foo', 'bar')) works as expected.
// Because of that, placeholders must NOT be put inside the array. To bind the list as a parameter,
// pass the placeholder as a string: $qb->expr()->in('u.id', ':ids') and call $qb->setParameter('ids', array(1, 2, 3))
public function in($x, $y); // Returns Expr\Func instance

// Example - $qb->expr()->notIn('u.id', '2')
Expand Down
8 changes: 8 additions & 0 deletions docs/en/reference/transactions-and-concurrency.rst
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,14 @@ timestamp or datetime):
</entity>
</doctrine-mapping>

The version column is never part of the ``INSERT`` statement. Its initial
value is set by the database through the column default, and Doctrine reads
it back after the insert. When the schema is generated with the
:doc:`SchemaTool <tools>`, Doctrine adds the default automatically: ``1`` for
integer types and ``CURRENT_TIMESTAMP`` for the ``datetime`` type. If you manage
your schema in a different way, make sure the version column has such a
default, otherwise inserting new entities fails with a ``NOT NULL`` violation.

Version numbers (not timestamps) should however be preferred as
they can not potentially conflict in a highly concurrent
environment, unlike timestamps where this is a possibility,
Expand Down
Loading
Loading