Using discriminator in an entity that extends another

I am trying to use Discriminator in an entity that extends from another. This is the code I made:

 /** * @ORM\Entity * @ORM\Table(name="usuarios_externos.usuarios", schema="usuarios_externos") * @ORM\InheritanceType("JOINED") * @ORM\DiscriminatorColumn(name="discr", type="string") * @ORM\DiscriminatorMap({ * "natural" = "Natural", * "empresa" = "Empresa" * }) * @UniqueEntity(fields={"correo_alternativo"}, message="El correo electrónico ya está siendo usado.") * @Gedmo\SoftDeleteable(fieldName="deletedAt", timeAware=false) */ class Usuario extends BaseUser { .... } 

But I get this error when running the doctrine:schema:validate command:

[Doctrine \ ORM \ Mapping \ MappingException] The entity 'UsuarioBundle \ Entity \ Usuario' must be part of the discriminator map "UsuarioBundle \ Entity \ Usuario" must be correctly mapped to the inheritance hierarchy. Alternatively, you can make 'UsuarioBundle \ Entity \ Usuario' an abstract class to avoid this exception from happening.

Any way to fix this? Can I use the discriminator in extended classes?

+8
php mapping orm symfony doctrine2
source share
1 answer

The answer is directly in the warning message!

Basically, he tells you that Usuario is defined in a way that can lead to trouble. In the current form, this code allows you to create an instance of Usuario and work with it. But wait a second. This is not defined on the discriminator card. So what happens when you try to save it? Boom! ... or at least it will throw an ugly exception.

Now I know that you probably didn’t even think about creating an instance of Usuario . This is just the base class for Natural and Empresa , but Doctrine does not know what .

So how can you fix this? Two scenarios are possible depending on your needs:

Usuario must be realistic

That is, users in your application can be instances of Natural , Empresa or just Usuario . This is probably not the case, but may be applicable to the future reader.

Solution: Add Usuario to the discriminator card. This will allow your users to be one of three types.

  * ... * @ORM\DiscriminatorMap({ * "usuario" = "Usuario", * "natural" = "Natural", * "empresa" = "Empresa" * }) * ... 

Usuario doesn't have to be realistic

That is, users in your application can be either an instance of Natural or Empresa , but never Usuario .

Solution: make the Usuario class abstract . This will make it impossible to instantiate.

 abstract class Usuario extends BaseUser { ... 
+24
source share

All Articles