Search code examples
phpsymfonydoctrine-orm

How to embedded a collection of object with doctrine using attribute #[Embedded]?


Assume we have a simple entity User that contains an attribute $addresses and this one holds a collection of Address objects, how to do this with doctrine (doc) ?

This is my test :

<?php
use Doctrine\ORM\Mapping\Embeddable;
use Doctrine\ORM\Mapping\Embedded;

#[Embeddable]
class Address
{
    private string $name;
}

class User
{
    #[Embedded(class: Address::class.'[]')]
    private array $addresses;
}

In this example, this doesn't work, because when I retrieve a record of User, the property $address only represents a bi-dimensional array instead of an array of Address instances.


Solution

  • In the definition of class User, here is your mistake.

    private array $address;
    

    This should be :

    private Address $address;
    

    Unfortunately, you can’t use Embeddables to implement complex associations and Doctrine ORM has no plan to do it.

    For this, you will have to use a more classic OneToMany Doctrine association.