gpt4 book ai didi

mysql - Doctrine2 与 Symfony2 : Why does cascade persist not work on this many-to-many relationship?

转载 作者:行者123 更新时间:2023-11-29 08:35:12 26 4
gpt4 key购买 nike

在我的项目中,我有许多多对多实体。这种多对多关系具有属性,因此我决定将它们分成A 1:n B n:1 C,就像is described in this post .

所以我的简化类结构如下所示。到目前为止一切顺利,但是当我运行 Controller (也在下面列出)插入值时出现异常:

An exception occurred while executing 'INSERT INTO b (...) VALUES (...)' with params {...}

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'class_a_id' cannot be null

我做错了什么?

A类

<?
/**
* @ORM\Entity
* @ORM\Table(name="a")
*/
class ClassA {
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
**/
protected $id;

/** OTHER FIELDS **/

/**
* @ORM\OneToMany(targetEntity="ClassB", mappedBy="class_a", cascade={"persist", "remove"})
**/
protected $class_b;
}

B 类

/**
* @ORM\Entity
* @ORM\Table(name="b")
*/
class ClassB {
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
**/
protected $id;
/**
* @ORM\ManyToOne(targetEntity="ClassC", inversedBy="class_b")
* @ORM\JoinColumn(name="class_c_id", referencedColumnName="id", nullable=false)
**/
protected $class_c;
/**
* @ORM\ManyToOne(targetEntity="ClassA", inversedBy="class_b")
* @ORM\JoinColumn(name="class_a_id", referencedColumnName="id", nullable=false)
**/
protected $class_a;

/** OTHER FIELDS **/
}

C 类

/**
* @ORM\Entity
* @ORM\Table(name="c")
*/
class ClassC {
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;

/** OTHER FIELDS **/

/**
* @ORM\OneToMany(targetEntity="ClassB", mappedBy="class_c")
**/
protected $class_b;
}

Controller

$em = $this->getDoctrine()->getEntityManager();
$a = new ClassA();
$a->setXXX() //Setting some other fields
foreach(...) {
$b = new ClassB();
$b->setClass_C(...); //found by doctrine out of database and set into classB
$b->setXXX() //Setting some other fields
$a->addClass-B($b); //added ClassB into ClassA
}
$em->persist($a);
$em->flush();

最佳答案

感谢您考虑我的问题,但已经解决了!只需将类 a 添加到 b 中即可轻松解决该问题。所以我的 Controller 现在可以工作了。请参阅下面的差异:

Controller

$em = $this->getDoctrine()->getEntityManager();
$a = new ClassA();
$a->setXXX() //Setting some other fields
foreach(...) {
$b = new ClassB();
$b->setClass_C(...); //found by doctrine out of database and set into classB
$b->setXXX() //Setting some other fields
$a->addClass-B($b); //added ClassB into ClassA
$b->setClass_A($a); //add ClassA into Class B !!NEW!!
}
$em->persist($a);
$em->flush();

关于mysql - Doctrine2 与 Symfony2 : Why does cascade persist not work on this many-to-many relationship?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15443375/

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