Search code examples
phpsymfonydoctrine-orm

Symfony Entity Factory with DiscriminatorColumn not working


I have this entity Contact.php

#[ORM\DiscriminatorColumn(name: 'type', type: 'string')]
#[ORM\DiscriminatorMap([
    'person' => ContactType\Person::class,
    'family' => ContactType\Family::class,
    'company' => ContactType\Company::class,
])]

and also the Factory like this:

protected function getDefaults(): array
    {
        return [
            'createdAt' => self::faker()->dateTime(),
            'isArchived' => 0,
            ...
            'type' => Person::class,
        ];
    }

In my AppFixtures file I have something like this:

public function load(ObjectManager $manager): void
    {
        $user = UserFactory::createOne();
        $contacts = ContactFactory::createMany(5, [
            'createdBy' => $user
        ]);

        $manager->flush();
    }

calling the command php bin/console doctrine:fixtures:load is ending up in this error:

In Instantiator.php line 84:
                                                                                           
  Cannot set attribute "type" for object "App\Entity\Contact" (not public and no setter).  
                                                                                           

In PropertyAccessor.php line 544:
                                                                                      
  Could not determine access type for property "type" in class "App\Entity\Contact".  
                                                                                      

My goal here is to have working Fixtures so I can test the code or just create myself dummy data. I have no idea what to do in this or even where to look. Any suggestions are more then welcomed.


Solution

  • DiscriminatorColumn and DisciminatorMap is used by Class Table Inheritence (https://www.doctrine-project.org/projects/doctrine-orm/en/2.17/reference/inheritance-mapping.html#class-table-inheritance).

    You specify 3 mapped types (each one is present in DiscriminatorMap) : Person, Family and Company.

    #[ORM\DiscriminatorMap([
        'person' => ContactType\Person::class,
        'family' => ContactType\Family::class,
        'company' => ContactType\Company::class,
    ])]
    

    But the exception say you trying to create a Contact and there is no type on it.

    Can you edit your question with ContactFactory ? Did you create a Contact class or a Person class ?