Skip to content

[Validator] UniqueEntity constraint can fail when using inheritance #4087

Closed
@datiecher

Description

@datiecher

Currently, the UniqueEntity constraint can fail when used on an inherited Entity, depending on where the validated field was declared in the Inheritance chain. Let me give you an example, suppose we have defined the following classes, where both Student and Teacher extend Person and we have used Doctrine's Class Table Inheritance:

<?php

Class Person
{
    /**
     * @UniqueEntity("name")
     */
    private $name;
}

Class Student extends Person { }

Class Teacher extends Person { }

Now let's insert a new Teacher named "Fabien", the validator kicks in, see that no Teacher with that name exists and "Fabien" is happily inserted on the database (inside the person table).

Trying to insert another Teacher with the same name works as expected, stating that our unique constraint was violated.

Now, if we try to insert a new Student whose name is "Fabien" as well the validator fails to do its work, letting this violation pass unseen and then when Doctrine tries to persist the new Student (assuming your name is a unique field, which probably should) the database will yell back at you saying that another record with the same name already exists in the person table.

This happens because the validator uses the repository of the entity in which the validation was triggered, not the repository in which the field was defined. So a SQL similar to this is generated:

SELECT * FROM student INNER JOIN person ON student.id = person.id WHERE person.name = 'Fabien'

And because of the fact that no Student with the name "Fabien" exists (we have added a Teacher with the name "Fabien") the validation will not work properly.

I'm currently working on a fix for this issue so a PR will follow shortly.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions