在我的项目中,我有很多many-to-many
个实体。这个many-to-many
关系具有属性,所以我决定将它们分解为A 1:n B n:1 C
,就像它is described in this post一样。
所以我的简化类结构如下所示。到目前为止一切都那么好,但是当我运行我的控制器(也在下面列出)插入值时,我得到了一个异常:
使用params {...}执行'INSERT INTO b(...)VALUES(...)'时发生异常
SQLSTATE [23000]:完整性约束违规:1048列'class_a_id'不能为空
我做错了什么?
<?
/**
* @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;
}
/**
* @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 **/
}
/**
* @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;
}
$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();
答案 0 :(得分:2)
感谢您思考我的问题,但已经解决了! 通过在b中添加a类,可以轻松解决问题。所以我的控制器现在工作。请参阅以下差异:
$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();