php - Symfony2:如何避免数据库中已经存在重复的实体?

原文 标签 php mysql entity-framework symfony doctrine-orm

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

I have the entities "Student" and "Parents" in two forms, one embedded in another are Symfony2. I need to store data from both entities in different tables of the database, when a new student and his parents also adds added. But I need that parents are not duplicated in the database, so before adding have to check that there are none, add only in that case. I do not know how to do this in Symfony2. More information is another question I asked.

look the other question here

I hope someone can help me because I can not find a solution for this problem.

Answer

In order to have columns with unique entries you must use UniqueEntity Validation constraint 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.

add @UniqueEntity("parent") above your entity name and unique=true on the field that you want to be unique

form the docs

// 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;

    // ...
}

翻译

我有两种形式的实体“ Student”和“ Parents”,一种嵌入在另一种形式中是Symfony2。我需要将来自两个实体的数据存储在数据库的不同表中,同时还要增加一个新学生及其父母。但是我需要父母在数据库中不重复,因此在添加之前必须检查是否没有父母,仅在这种情况下添加。我不知道如何在Symfony2中执行此操作。我问的另一个问题是更多信息。

look the other question here

我希望有人可以帮助我,因为我找不到解决此问题的方法。
最佳答案
为了使列具有唯一条目,您必须使用UniqueEntity Validation约束Docs


  验证Doctrine实体中的一个或多个特定字段是否唯一。这通常用于防止新用户使用系统中已存在的电子邮件地址进行注册。


在实体名称上方添加@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 - Eclipse中的PHP 7调试器设置

javascript - 访问URL参数-PHP和Angular.js

php - 使用更新的MySQL库修复PHP数据库连接失败

php - PHP代码不允许多个输入值通过我的表单发送

php - Laravel 5.1内部联接查询中的问题

php - 控制PHP ldap分页-结果数和页码

php - 带有PHPStorm 10的PHP7

php - 如何防止第二个正则表达式重新替换?

php - 如何在PHP的$ _SESSION中保存值并进行检索

php - 与特质的定义顺序和内容有关的“未找到特质错误”