php - Symfony2 : How to avoid duplicate entities that already exist in the database?

标签 php mysql entity-framework symfony doctrine-orm

我有两种形式的实体“学生”和“ parent ”,一种嵌入另一种形式是 Symfony2。我需要将来自两个实体的数据存储在数据库的不同表中,当一个新学生和他的 parent 也添加时。但是我需要 parent 在数据库中不重复,所以在添加之前必须检查没有,只有在这种情况下才添加。我不知道如何在 Symfony2 中执行此操作。更多信息是我问的另一个问题。

look the other question here

我希望有人能帮助我,因为我找不到解决这个问题的方法。

最佳答案

为了让列具有唯一条目,您必须使用 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/

相关文章:

php - 在我的 PHP 留言板中,如何输出与相应帖子相对应的图像?

entity-framework - SQL Server Express 和 Entity Framework

javascript - 将 iframe 与 jquery 一起使用

php - MySQL表索引

javascript - 我如何使用 JS 和 AJAX 发送数组

php - 将 Mysql 查询转换为 Magento 查询

php - 为 WordPress 上传文件的权限问题

python - pip install mysqlclient 返回 "fatal error C1083: Cannot open file: ' mysql.h' : No such file or directory

entity-framework - 尝试序列化 Entity Framework 对象时出现 XML 序列化错误

c# - 将不同的模型类型从 Controller 传递到 View 是好的做法吗?