當我提交表單并持久化對象模型時,出現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有點令人困惑。
- 1 回答
- 0 關注
- 192 瀏覽
添加回答
舉報
0/150
提交
取消