doctrine 一对多关系 可选

现存Article,Category两个entity,关系为onetomany;
其中article不是必须对应category,如果article不存在对应的分类,那么category_id =0;

那么问题来了

$article = new Article();
$article->setTitle('This is a test article');
//...
$em->persist($article);
$em->flush();

报错如下,category_id 不能为空

  [Doctrine\DBAL\Driver\PDOException]
  SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'category_id' cannot be null



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

这种非必须的Association怎么设置呢

阅读 3.1k
1 个回答

把 Article::$category 的 nullable 属性设为 true 就可以了

``
class Article
{

/**
 * @ORM\OneToMany(targetEntity="AppBundle\Entity\Category", nullable=true)
 */
protected $category;

}
``

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进