来自另一个OneToOne协会的PFK的Doctrine 2 OneToOne

时间:2016-02-15 22:36:01

标签: php doctrine-orm

我有一个问题。我正在使用 Doctrine 2.0 ,我想知道是否可以通过使用由另一个 OneToOne <创建的 PFK 来建立 OneToOne 关联/ strong> assotiation,如下图所示。

enter image description here

我的代码如下所示:

用户类:

/**
 * @ORM\Entity()
 */
class User extends \Kdyby\Doctrine\Entities\IdentifiedEntity
{

    /**
     * @ORM\OneToOne(targetEntity="AllianceMember", mappedBy="user")
     * var AllianceMember
     */
    protected $allianceMembership;
}

AllianceMember班:

/**
 * @ORM\Entity()
 */
class AllianceMember extends \Kdyby\Doctrine\Entities\BaseEntity
{
    /**
     * @ORM\Id
     * @ORM\OneToOne(targetEntity="User", inversedBy="allianceMembership")
     * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false)
     * @var User
     */
    protected $user;

    /**
     * @ORM\OneToOne(targetEntity="AllianceRole", mappedBy="allianceMember")
     * var AllianceRole
     */
     protected $role;

AllianceRole课程:

/**
 *
 * @ORM\Entity()
 */
class AllianceRole extends \Kdyby\Doctrine\Entities\BaseEntity
{
    /**
     * @ORM\Id
     * @ORM\OneToOne(targetEntity="AllianceMember", inversedBy="role")
     * @ORM\JoinColumn(name="role_id", referencedColumnName="user_id", nullable=false)
     * @var AllianceMember
     */
    protected $allianceMember;
}

当我尝试获取用户实体的实例时,我收到此错误:

The column user_id must be mapped to a field in class App\Entity\AllianceMember since it is referenced by a join column of another class.

甚至可能吗?

感谢。

1 个答案:

答案 0 :(得分:2)

是的,因为学说2.1见Primary key and foreign key at the same time with doctrine 2

,所以可以使用@Id的映射实体

我认为您只需要删除部分JoinColumn语句。由于@user已被指定为@Id,因此无需将user_id指定为JoinColumn:

/**
 * @ORM\Entity()
 */
class AllianceMember extends \Kdyby\Doctrine\Entities\BaseEntity
{
    /**
     * @ORM\Id
     * @ORM\OneToOne(targetEntity="User", inversedBy="allianceMembership")
     * @var User
     */
    protected $user;

    /**
     * @ORM\OneToOne(targetEntity="AllianceRole", mappedBy="allianceMember")
     * var AllianceRole
     */
     protected $role;

/**
 *
 * @ORM\Entity()
 */
class AllianceRole extends \Kdyby\Doctrine\Entities\BaseEntity
{
    /**
     * @ORM\Id
     * @ORM\OneToOne(targetEntity="AllianceMember", inversedBy="role")
     * @var AllianceMember
     */
    protected $allianceMember;
}

AllianceMember的id是user_id,AllianceRole的id是AllianceMember的id,即user_id。