简体   繁体   English

Symfony-更新唯一的OneToMany关系属性

[英]Symfony - Update a unique OneToMany relation property

A Company can have multiple emails and all emails have to be unique. 一个公司可以有多个电子邮件,并且所有电子邮件都必须是唯一的。
This my Entites for Company and CompanyEmail 这是我公司和公司电子邮件的实体

CompanyEmail Entity: CompanyEmail实体:

/**
 * @ORM\Entity(repositoryClass="App\Repository\CompanyEmailRepository")
 * @UniqueEntity("name")
 */
class CompanyEmail
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=128, unique=true)
     * @Assert\Email()
     */
    private $name;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Company", inversedBy="emails")
     * @ORM\JoinColumn(nullable=false)
     */
    private $company;

    // ...
}

Company Entity: 公司实体:

/**
 * @ORM\Entity(repositoryClass="App\Repository\CompanyRepository")
 */
class Company
{
    // ...

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\CompanyEmail", mappedBy="company", orphanRemoval=true, cascade={"persist"})
     * @Assert\Valid
     */
    private $emails;

    // ...
}

and I'm using an custom EmailsInputType that use this DataTransformer 我正在使用使用此DataTransformer的自定义EmailsInputType

class EmailArrayToStringTransformer implements DataTransformerInterface
{
    public function transform($emails): string
    {
        return implode(', ', $emails);
    }


    public function reverseTransform($string): array
    {
        if ($string === '' || $string === null) {
            return [];
        }

        $inputEmails = array_filter(array_unique(array_map('trim', explode(',', $string))));

        $cEmails = [];
        foreach($inputEmails as $email){
            $cEmail = new CompanyEmail();
            $cEmail->setName($email);
            $cEmails[] = $cEmail;
        }

        return $cEmails;
    }
}

and in the Controller a use this edit method 并在Controller中使用此编辑方法

/**
     * @Route("/edit/{id}", name="admin_company_edit", requirements={"id": "\d+"}, methods={"GET", "POST"})
     */
    public function edit(Request $request, $id): Response
    {
        $entityManager = $this->getDoctrine()->getManager();
        $company = $entityManager->getRepository(Company::class)->find($id);

        $form = $this->createForm(CompanyType::class, $company);

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $entityManager->flush();
        }
    }

There is two problems with this code 此代码有两个问题

1 - In the edit form when i try to keep an already saved email Symfony generate a validation error that tells that this email is already exits. 1-在编辑表单中,当我尝试保留已保存的电子邮件时,Symfony会生成一个验证错误,告诉您该电子邮件已退出。

2 - When I remove the validation restriction from the code, Symfony thrown the database error "*Integrity constraint violation: 1062 Duplicate entry ... *" 2-当我从代码中删除验证限制时,Symfony抛出数据库错误“ *完整性约束冲突:1062复制条目... *”

What i should do to make my code work as expected ! 我应该怎么做才能使我的代码按预期工作!

The problem is right here 问题就在这里

public function reverseTransform($string): array
{
  [...]

  foreach($inputEmails as $email){
    $cEmail = new CompanyEmail();
    [...]
  }

  [...]
}

You need to retrieve the email instead of creating new one. 您需要检索email而不是创建新email So basically, inject a CompanyEmailRepository , try to find if email already exists ( findOneBy(['name']) ), if it does not exists, create a new one but if exists, use what you've retrieved. 因此,基本上,注入一个CompanyEmailRepository ,尝试查找是否已经存在电子邮件( findOneBy(['name']) ),如果不存在,则创建一个新电子邮件,但如果存在,则使用您检索的内容。

Just few notes 只是一些笔记

  • Pay attention to email owner (so the retrieve should be do per user I guess as no one can share the same mail UNLESS you can specify some aliases or shared address) 注意电子邮件所有者(因此检索应该针对每个用户,因为我猜没有人可以共享同一封邮件,除非您可以指定一些别名或共享地址)
  • Maybe you don't need an extra entity like CompanyEmail as you can use a json field where you can store them in a comma separated fashion (unless you need some extra parameters or unless you need to perform some indexing/querying operation on the emails) 也许您不需要像CompanyEmail这样的额外实体,因为您可以使用json字段,以逗号分隔的方式存储它们(除非您需要一些额外的参数,或者除非您需要对电子邮件执行一些索引/查询操作)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM