1

I'm developing a custom user bundle for a symfony2 application which has 3 types of users: Administrator, Professor and Student. Each type of user has an identifier (the national identity number, in Spanish: dni) and another data like name, lastName, etc. (data between different user's type are disjoint)

My problem is that I need that a dni is never repeated, regardless of the user's type.

I have used the UniqueEntity annotation and this works, but only with entities of the same type.

How I could do it for entities of different type?

I have thought to use the callback annotation and check with a query that in the other entities there is no entity with that dni but for that I have to use the entity manager inside of an entity and this is a bad practise.

Do exist another way to do this?

Greetings and thanks.

4

3 回答 3

1

解决了。这是最后的片段(感谢 ladislav_prague)

$repository_a = $this->getDoctrine()->getRepository('AppBundle:Administrator');
    $administrator_dni_used = $repository_a->createQueryBuilder('a')->where('a.dni = \'' . $dni_to_check . '\'')->getQuery()->getOneOrNullResult();

$repository_p = $this->getDoctrine()->getRepository('AppBundle:Professor');
$professor_dni_used = $repository_a->createQueryBuilder('p')->where('p.dni = \'' . $dni_to_check . '\'')->getQuery()->getOneOrNullResult();

$repository_s = $this->getDoctrine()->getRepository('AppBundle:Student');
$student_dni_used = $repository_a->createQueryBuilder('s')->where('s.dni = \'' . $dni_to_check . '\'')->getQuery()->getOneOrNullResult();


if(is_null($administrator_dni_used) and is_null($professor_dni_used) and is_null($student_dni_used)){

// add new user

}else{

    $error = new FormError("There is already an user with that dni");
    $editForm->get('dni')->addError($error);
    // ...
}
于 2013-11-11T12:04:38.993 回答
0

如果最后插入的用户的 dni 可能小于第一个用户,则在创建新用户之前检查现有的 dni。像这样:

$repository_a = $this->getDoctrine()->getRepository('AppBundle:Administrator');
$administrator_dni_used = $repository_a->createQueryBuilder('a')->where('a.dni = \'' . $dni_to_check . '\'')->getQuery()->getOneOrNullResult();

$repository_p = $this->getDoctrine()->getRepository('AppBundle:Professor');
$professor_dni_used = $repository_a->createQueryBuilder('p')->where('p.dni = \'' . $dni_to_check . '\'')->getQuery()->getOneOrNullResult();

$repository_s = $this->getDoctrine()->getRepository('AppBundle:Student');
$student_dni_used = $repository_a->createQueryBuilder('s')->where('s.dni = \'' . $dni_to_check . '\'')->getQuery()->getOneOrNullResult();


if(is_null($administrator_dni_used) and is_null($professor_dni_used) and is_null($student_dni_used)){

// add new user

}
于 2013-11-11T11:40:59.350 回答
0

只需创建一个新实体(我们称之为 Dni),它从所有表中收集 dni 值,例如通过 OneToOne 关联与每个现有实体关联的 AdministratorDni、ProfessorDni 和 StudentDni 属性。

然后每次在添加新的管理员/教授/学生之前,创建一个学说查询以从 AdministratorDni、ProfessorDni 和 StudentDni 中选择最大值。您将获得三个最新的 dni 最大值,因此只需使用 max() 函数即可获得实际的最高 dni。

于 2013-11-11T07:44:48.513 回答