简体   繁体   English

在Symfony中插入带有父项的子实体

[英]Inserting a child entity with parent in Symfony

I have a parent entity which is referring to a child entity and the classes are written as follows: 我有一个父实体,它引用一个子实体,其类编写如下:

class MyEntity {
  /**
  * ORM Annotations
  */
  private $id;

  /**
  * ORM Annotations
  */
  private $name;

  /**
  * @var string
  * @ORM\OneToOne(targetEntity="Picture")
  */
  private $image;

  /** Getters & Setters **/
}

private Image {
  private $id;
  private $image_url;
}

Here, Image is a weak entity and I don't want to insert image before inserting MyEntity object. 在这里,Image是一个弱实体,我不想在插入MyEntity对象之前插入图像。 Basically, my question is, how can I render the form for MyEntity so that, Image form appears as a part of it, and image get saved when I save MyEntity . 基本上,我的问题是,如何呈现MyEntity的表单,以便Image表单显示为表单的一部分,并在保存MyEntity时保存图像。

How come your code has targetEntity="Picture" and you have defined Image as child Entity. 您的代码为什么会有targetEntity="Picture"并且已将Image定义为子Entity。 I guess there is a typo, you need to correct. 我猜有一个错字,您需要纠正。

You need to add cascade={"persist", "update"} to your image association in MyEntity . 您需要在MyEntityimage关联中添加cascade={"persist", "update"}

This will make sure, Image entity being created / updated along with MyEntity . 这将确保与MyEntity一起创建/更新的Image实体。

Now the form Part 现在表格部分

Create a new FormType for Image , lets call it as ImageType . Image创建一个新的FormType ,将其称为ImageType In your MyEntity FormType, add the new FormType as a new field : 在您的MyEntity FormType中,将新的FormType添加为新字段:

$builder
    ->add('image', ImageType::class, array(
        'label' => 'Image'
));

Now on form Submission, The child entity (Image) will be created / updated accordingly. 现在,在“提交”表单中,将相应地创建/更新子实体(图像)。

Note : You need to take care of image upload explicitly. 注意 :您需要明确处理图片上传。

Hope this helps! 希望这可以帮助!

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

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