【发布时间】:2012-09-05 18:06:20
【问题描述】:
一个用户可能只有 1 项,也可能没有。 (1-1..0关系)
我正试图在 symfony2 中通过教义来实现这一点。
我已经完成了一对一的关系,这相当简单。但是我如何指定当我想创建一个用户时,该项目可以为空? (而不是插入一个新行,只是让 id_item 为空)
这就是我所拥有的:
user.orm.yml 文件
oneToOne:
userItem:
targetEntity: SOA\AXBundle\Entity\Items
cascade: ["remove", "persist"]
joinColumn:
name: id_item
referencedColumnName: id
nullable: true
当然,我创建了 ItemsTypeForm 类,并在我的 userstypeform 类中添加了类型:
// UsersTypeForm Class
->add('userItem', new \SOA\AXBundle\Form\ItemsTypeForm())
Controller Action 是这样的,
public function addUserAction(Request $request) {
$user = new User();
$form = $this->createForm(new UseType(), $user);
if ($request->getMethod() == 'POST') {
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($user);
$em->flush();
return $this->redirect($this->generateUrl('homepage'));
}
}
}
当我添加一个新用户时,一切正常。用户和项目一样被插入。但是当我尝试添加一个没有项目的用户(用户项目字段为空白)时,我收到以下错误:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'name' cannot be null
它正在尝试插入具有空值的项目。
虽然我可以接受一对一的关系,但我想学习如何建立一对一的关系。
【问题讨论】:
-
你能展示一下你是如何持久化数据的吗?
标签: php symfony doctrine doctrine-orm