简体   繁体   English

具有多个表的学说OneToOne

[英]Doctrine OneToOne with multiple tables

Im using doctrine 2 and zend framework 3. I got an entity "Project" with an OneToOne Relation to "projectdetails". 我使用的是教义2和zend框架3。我得到了一个与“ projectdetails”具有一对一关系的实体“ Project”。 ProjectDetails is split between multiple tables depending on a the Project field "type". 根据Project字段“类型”,ProjectDetails会在多个表之间拆分。

Is there an easy way to tell doctrine which table to use for the projectdetails depending on the type field Value? 有没有一种简单的方法可以根据类型字段Value告诉教义要在项目中使用哪个表的详细信息?

You can define "OneToOne" associations for each of the projectdetails tables: 您可以为每个projectdetails表定义“ OneToOne”关联:

/**
 * @OneToOne(targetEntity="ProjectDetails1")
 * @JoinColumn(name="project_details_id", referencedColumnName="id")
 */
private $projectDetails1;

/**
 * @OneToOne(targetEntity="ProjectDetails2")
 * @JoinColumn(name="project_details_id", referencedColumnName="id")
 */
private $projectDetails2;

Add any more projectdetails tables. 添加更多的projectdetails表。 Then use a getter function to get the correct relation based on type: 然后使用getter函数根据类型获取正确的关系:

function getProjectDetails() {
    if($this->type === 'type1') {
        return $this->projectDetails1;
    }
    elseif($this->type === 'type2') {
        return $this->projectDetails2;
    }
}

Update : In this case you cannot use doctrine console tool to generate your associations, as it will be impossible to set the foreign key on "project_details_id" to 2 different tables. 更新 :在这种情况下,您将无法使用教义控制台工具生成关联,因为不可能将“ project_details_id”上的外键设置为2个不同的表。

To solve this, the column project_details_id of integer type should be created with a migration or you can define a field in the Project entity: 要解决此问题,应使用迁移创建整数类型的列project_details_id ,或者您可以在Project实体中定义字段:

/**
 * @ORM\Column(type="integer", nullable=true)
 */
private $projectDetailsId;

generate & run the migration. 生成并运行迁移。 Finally replace the latter field with the above associations. 最后,用上述关联替换后一个字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM