亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

表單 OneToMany 外鍵空值沖突

表單 OneToMany 外鍵空值沖突

PHP
江戶川亂折騰 2021-12-03 14:33:34
當我提交表單并持久化對象模型時,出現SQLSTATE[23502]: Not null violation: 7 ERROR: null value in column "object_id"錯誤。我有兩個 Doctrine 實體:class Object {    /**     * @var Document[]|ArrayCollection     * @ORM\OneToMany(targetEntity="App\Entity\Document", mappedBy="mainObject", cascade={"persist"})     */    private $documents;}class Document{    /**     * @ORM\ManyToOne(targetEntity="App\Entity\Object", inversedBy="documents")     * @ORM\JoinColumn(nullable=false)     */    private $object;}和 Symfony 形式:class ObjectType extends AbstractType{    public function buildForm(FormBuilderInterface $builder, array $options)    {        $builder            ->add('documents', CollectionType::class, [                'allow_add' => true,                'entry_type' => DocumentType::class,            ])        ;    }}我的控制器代碼:$object = new Object();$form = $this->formFactory->create(ObjectType::class, $object);$form->submit(json_decode($request->getContent(), true), false);if ($form->isSubmitted() && $form->isValid()) {    $this->entityManager->persist($object);    $this->entityManager->flush();}發生錯誤是因為 Doctrine 將 Document 保存在 Object 之前。是否可以更改保存行為?
查看完整描述

1 回答

?
精慕HU

TA貢獻1845條經驗 獲得超8個贊

為了解決這個問題,您可以by_reference => false在集合類型上使用。通過將此設置為 false,您是在說始終使用方法而不是訪問屬性。


$builder

    ->add('documents', CollectionType::class, [

        'allow_add' => true,

        'entry_type' => DocumentType::class,

        'by_reference' => false,

    ]);

在某些情況下,將直接使用屬性而不是方法。您可以在此處閱讀有關此屬性的更多信息。


在對象的addDocument()方法上添加新文檔時,您還需要設置對象。這應該類似于:


public function addDocument(Document $document): object

{

    $document->setObject($this);


    $this->getDocuments()->add($document);


    return $this;

}

那應該可以解決您的問題。我也認為命名實體object有點令人困惑。


查看完整回答
反對 回復 2021-12-03
  • 1 回答
  • 0 關注
  • 192 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號