Doctrine: authorize NULL in a foreign composite ke

2019-08-27 20:33发布

I have the following entity:

/**
 * 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
}

The idea behind it is quite simple: We have author, role and series entities. A series can have several authors with various roles. A same author can fulfill multiple roles in a series.

Sometimes, we don't know exactly what was the role of the author. In this case, the NULL value will be used for the role, the NULL value standing for "I don't know".

I was taught not to use NULL in foreign composite keys unless it has meaning. Well, it has meaning here, and I know that this could be implemented without Doctrine. However, for now, Symfony 2 throws that error:

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

So how can I authorize NULL values in foreign composite keys ? Is it possible at all with Doctrine ?

1条回答
【Aperson】
2楼-- · 2019-08-27 21:08

Your @JoinColumn annotation is correct with referencing to http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/annotations-reference.html#annref-joincolumn

However,

Every entity with a composite key cannot use an id generator other than “ASSIGNED”. That means the ID fields have to have their values set before you call EntityManager#persist($entity).

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

查看更多
登录 后发表回答