我有两种形式的实体“学生”和“ parent ”,一种嵌入另一种形式是 Symfony2。我需要将来自两个实体的数据存储在数据库的不同表中,当一个新学生和他的 parent 也添加时。但是我需要 parent 在数据库中不重复,所以在添加之前必须检查没有,只有在这种情况下才添加。我不知道如何在 Symfony2 中执行此操作。更多信息是我问的另一个问题。
我希望有人能帮助我,因为我找不到解决这个问题的方法。
最佳答案
为了让列具有唯一条目,您必须使用 UniqueEntity Validation 约束 Docs
Validates that a particular field (or fields) in a Doctrine entity is (are) unique. This is commonly used, for example, to prevent a new user to register using an email address that already exists in the system.
在您的实体名称上方添加 @UniqueEntity("parent")
并在您希望唯一的字段上添加 unique=true
形成文档
// src/AppBundle/Entity/Author.php
namespace AppBundle\Entity;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;
// DON'T forget this use statement!!!
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* @ORM\Entity
* @UniqueEntity("email")
*/
class Author
{
/**
* @var string $email
*
* @ORM\Column(name="email", type="string", length=255, unique=true)
* @Assert\Email()
*/
protected $email;
// ...
}
关于php - Symfony2 : How to avoid duplicate entities that already exist in the database?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34464065/