简体   繁体   中英

Doctrine2 Class Table Inheritance

I am a little bit confused by Doctrine's documentation so maybe you can help me. I have the following class inheritance:

<?php

class User
{
   /**
    * @var int
    */
    private $_id;

   /**
    * @var Role
    */
    private $_role;
}

class Company extends User
{

}

class Customer extends User
{
    ...
}

class Role
{
   /**
    * @var int
    */
    private $_id;
}

?>

I want to store each class in a separate table. The role defines the type of user by an id. How would I solve this problem? I tried this:

<?php

/**
 * @Entity
 * @Table(name="user")
 * @InheritanceType("JOINED")
 * @DiscriminatorColumn(name="role_id", type="integer")
 * @DiscriminatorMap({"1" = "User", "2" = "Customer"})
 */
class User
{
    ...
}

?>

I am not sure how to handle the role class in this scenario.


Thank you for your answer. Now I tried this and got following error:

[Doctrine\DBAL\Schema\SchemaException]
There is no column with name '_id' on table 'customer'.

I have following code:

<?php

/**
 * Class Sb_User
 *
 * @Entity
 * @Table(name="user")
 * @InheritanceType("JOINED")
 * @DiscriminatorColumn(name="role_id", type="integer")
 * @DiscriminatorMap({"2" = "Sb_Customer", "8" = "Sb_Pos"})
 */
class Sb_User implements Sb_User_Interface
{
    /**
     * @Id
     * @GeneratedValue
     * @Column(name="id", type="integer")
     * @var int
     */
     protected $_id;

     ...
}

/**
 * Class Sb_Customer
 *
 * @Entity
 * @EntityResult(discriminatorColumn="role_id")
 * @Table(name="customer")
 *
 */
class Sb_Customer extends Sb_User implements Sb_Customer_Interface
{
    ....
}

I do not know what I am doing wrong. Can you help me?

?>

Your question is a bit confusing to me.

You want to use joined table inheritance to define the role of a user, but you also want to add a role attribute to your user that, as I understand, does exactly the same. Seems like you're trying to do the same thing twice in a different way.

Anyway, I will try to give you an answer.

If you want to use separate tables for each type (Customer, Company, etc) you should have a look at mapped superclasses: http://docs.doctrine-project.org/en/2.0.x/reference/inheritance-mapping.html#mapped-superclasses

That way you can define basic class attributes and relations that will be used by all the entities that extend it. All data will be saved in separate tables for each entity.

If you want to define the role of a user using the Role entity you should define a many-to-one relation between user and role.

Good luck!

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