【问题标题】:Doctrine: authorize NULL in a foreign composite key教义:在外部复合键中授权 NULL
【发布时间】:2014-03-25 11:08:23
【问题描述】:

我有以下实体:

/**
 * SeriesAuthorRole
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="Blog\Bundle\CoreBundle\Entity\SeriesAuthorRoleRepository")
 */
class SeriesAuthorRole extends AuthorRoleAbstract
{
    /**
     * @var Series
     *
     * @ORM\ManyToOne(targetEntity="Blog\Bundle\CoreBundle\Entity\Series", inversedBy="authors")
     * @ORM\JoinColumn(name="series", referencedColumnName="id", nullable=false)
     * @ORM\Id
     */
    private $series;

    /**
     * @var Author
     *
     * @ORM\ManyToOne(targetEntity="Blog\Bundle\CoreBundle\Entity\Author")
     * @ORM\JoinColumn(name="author", referencedColumnName="id", nullable=false)
     * @ORM\Id
     */
    protected $author;

    /**
     * @var Role
     *
     * @todo Must be nullable
     *
     * @ORM\ManyToOne(targetEntity="Blog\Bundle\CoreBundle\Entity\Role")
     * @ORM\JoinColumn(name="role", referencedColumnName="id", nullable=true)
     * @ORM\Id
     */
    protected $role;

    // ... Getters, setters
}

它背后的想法很简单:我们有作者、角色和系列实体。一个系列可以有多个不同角色的作者。同一个作者可以在一个系列中扮演多个角色。

有时,我们并不确切知道作者的角色是什么。在这种情况下,角色将使用 NULL 值,NULL 值代表“我不知道”。

我被教导不要在外部复合键中使用 NULL,除非它有意义。嗯,它在这里有意义,我知道这可以在没有 Doctrine 的情况下实现。然而,就目前而言,Symfony 2 抛出了这个错误:

Entity of type Blog\Bundle\CoreBundle\Entity\BandAuthorRole is missing an assigned ID for field 'role'. The identifier generation strategy for this entity requires the ID field to be populated before EntityManager#persist() is called. If you want automatically generated identifiers instead you need to adjust the metadata mapping accordingly.
500 Internal Server Error - ORMException

那么我怎样才能在外部复合键中授权 NULL 值呢? Doctrine 有可能吗?

【问题讨论】:

    标签: symfony doctrine-orm doctrine


    【解决方案1】:

    您的 @JoinColumn 注释在引用 http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/annotations-reference.html#annref-joincolumn 时是正确的

    然而,

    每个具有复合键的实体都不能使用其他的 id 生成器 比“分配”。这意味着 ID 字段必须有它们的值 在调用 EntityManager#persist($entity) 之前设置。

    http://docs.doctrine-project.org/en/2.0.x/tutorials/composite-primary-keys.html#general-considerations

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-20
      • 2016-07-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-20
      • 1970-01-01
      相关资源
      最近更新 更多