简体   繁体   中英

Doctrine 2.0: How to target an entity's superclass in a OneToOne relationship

I am not very good at asking questions but the code below should be self-explanatory. I need to create a OneToOne association from a class to an entity's superclass which is NOT an entity.

/* Not an entity */
class Superclass {
      /** 
       *@Id @Column(name="entity_id", type="integer") @GeneratedValue 
       **/
      protected $id;
}

/**
 * @Entity @Table(name="subclasses1")
 **/
class Subclass1 extends Superclass {

}

/**
 * @Entity @Table(name="subclasses2")
 **/
class Subclass2 extends Superclass {

}


/**
 * @Entity @Table(name="assoc")
 **/
class Associationclass
{
    /**
     *OneToOne(targetEntity="Superclass")
     **/
    protected $association;

    /**
     *@Column(type="string")
     **/
    protected $info;
}

The question is: How can I reference both subclass1 and subclass2 using the OneToOne relationship without making Superclass an Entity (creating a new table and using discriminators)?

You can't. If you want that sort of inheritance (the kind you can use in associations), you need to model the inheritance in doctrine.

The association needs a "targetEntity" -- which, like the name indicates, must be an entity.

Unless there's a very good reason not to, go ahead and make your superclass an entity, and set up the inheritance in a way doctrine can understand.

The reason your superclass needs to be an entity is because the superclass and it's subclasses will then share an identifier. So with the identifier (and the discriminator), doctrine can then figure out that SuperClass#1234 is actually a SubClass2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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