[英]Symfony OneToMany Relationship check if main (One) entity exists if inserting a new child (Many) entity
[英]Inserting a child entity with parent in Symfony
我有一個父實體,它引用一個子實體,其類編寫如下:
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;
}
在這里,Image是一個弱實體,我不想在插入MyEntity
對象之前插入圖像。 基本上,我的問題是,如何呈現MyEntity
的表單,以便Image
表單顯示為表單的一部分,並在保存MyEntity
時保存圖像。
您的代碼為什么會有targetEntity="Picture"
並且已將Image
定義為子Entity。 我猜有一個錯字,您需要糾正。
您需要在MyEntity
的image
關聯中添加cascade={"persist", "update"}
。
這將確保與MyEntity
一起創建/更新的Image實體。
現在表格部分
為Image
創建一個新的FormType
,將其稱為ImageType
。 在您的MyEntity
FormType中,將新的FormType添加為新字段:
$builder
->add('image', ImageType::class, array(
'label' => 'Image'
));
現在,在“提交”表單中,將相應地創建/更新子實體(圖像)。
注意 :您需要明確處理圖片上傳。
希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.