gpt4 book ai didi

php - Symfony2 创建和持久化实体关系

转载 作者:行者123 更新时间:2023-11-28 23:57:59 24 4
gpt4 key购买 nike

我有两个实体 SkinEmail。我希望 Email 成为 Skin 实体的一部分,但是我现在不能使用控制台自动更新架构,这可能就是我不能的原因让关系发挥作用。

所以我想将所有电子邮件存储在电子邮件实体中,并且我想将电子邮件分配给所需的皮肤。所以这种关系应该是 OneToOne。

我不是 MySQL 关系方面的专家,所以这是我自己做的:

在我的主要 Skin 类中,我创建了一个字段,我想在其中存储电子邮件 ID:

/**
*
* @ORM\OneToOne(targetEntity="MediaparkLt\UserBundle\Entity\Email", inversedBy="skin")
* @ORM\JoinColumn(name="email_id", referencedColumnName="id")
*/
protected $email_id;

在电子邮件类中,我创建了皮肤字段,我想在其中显示皮肤 ID:

/**
*
* @ORM\OneToOne(targetEntity="MediaparkLt\SkinBundle\Entity\Skin", mappedBy="email_id")
* @ORM\JoinColumn(name="skin", referencedColumnName="id")
*/
protected $skin;

现在在我的 CMS 中,我创建了这样的新电子邮件:

public function saveAction(Request $request) {
$item = new Email();
$type = new EmailType($this->container->getParameter("langs"));
$form = $this->createForm($type, $item);
$form->handleRequest($request);
$em = $this->getEntityManager();

if ($form->isValid()) {
$this->upload($form, $item);

$em->persist($item);
$em->flush();
return $this->redirect($this->generateUrl('cms_skin_email_list', array('skin_id' => $item->getId())));
}

return array('form' => $form->createView(), 'item' => $item);
}

这是表格:

public function buildForm(FormBuilderInterface $builder, array $option) {
$builder->add('title', 'text', array('label' => 'cms.Title'));
$builder->add('registration_content', 'textarea', array('label' => 'cms.registration.content'));
}

现在在 mysql 中我创建这样的关系:

ALTER TABLE `skin` ADD CONSTRAINT `emailId` FOREIGN KEY (`email_id`) REFERENCES `lottery`.`email`(`id`) ON DELETE RESTRICT ON UPDATE RESTRICT;

现在,当我创建一个新电子邮件时,我仍然在两个实体上得到 NULL。

最佳答案

当您创建两个具有一对一关系的实体时,这两个实体都需要显式持久化或通过在关系的一侧使用级联持久化来持久化。您还需要明确设置关系的双方。

Doctrine - Working with Associations - Transitive persistence / Cascade Operations

状态:

Even if you persist a new User that contains our new Comment this code would fail if you removed the call to EntityManager#persist($myFirstComment). Doctrine 2 does not cascade the persist operation to all nested entities that are new as well.

Doctrine - Working with Associations - Establishing Associations

状态:

In the case of bi-directional associations you have to update the fields on both sides

没有级联持续你需要这样的东西:

$skin = new Skin();
$email = new Email();
$skin->setEmail($email);
$email->setSkin($skin);
$em->persist($email);
$em->persist($skin);
$em->flush();

在关系的皮肤端使用级联持久化,您可以省略 $em->persist($skin)。请注意,如果您级联持久化,您通常也会级联删除:

 * @ORM\OneToOne(targetEntity="MediaparkLt\UserBundle\Entity\Email", inversedBy="skin", cascade={"persist", "remove"})

关于php - Symfony2 创建和持久化实体关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30981786/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com