4
votes

I'm having a problem extending an entity with the same database table name in symfony2. I'm trying to extend an entity in symfony, but the base entity needs to be reusable, so it will not always be extended.

This is a simplified example of what I currently have. My Customer entity:

namespace Bundle\Entity\Customer;

/**
 * @ORM\Table(name="customer")
 * @ORM\Entity()
 */
class Customer implements CustomerInterface, UserInterface
{
    //implementing variables and getters/setters
}

The extending entity (in another bundle):

namespace AnotherBundle\Entity\Customer;

use Bundle\Entity\Customer\Customer as BaseCustomer;

/**
 * @ORM\Entity()
 */
class Customer extends BaseCustomer
{
    //implementing variables and getters/setters
}

The CustomerInterface:

namespace Bundle\Model\Customer;

interface CustomerInterface
{
    // public methods of the first Customer class
}

In my config.yml i have the following rule:

resolve_target_entities:
        Bundle\Model\Customer\CustomerInterface: AnotherBundle\Entity\Customer\Customer

When generating the SQL I get the following error:

[Doctrine\DBAL\Schema\SchemaException]
The table with name 'customer' already exists.

I need the second entity to extend the first(base) entity and maintain the database table name. But when i don't extend the first(base) entity I still want this one to work on it's own.

I've tried this source but they couldn't solve my problem: Creating portable Bundles with extendable entities in Symfony2 (didn't work, although the entity was indeed mapped to the right one it still gave me the duplicate table name error)

Also, doctrine's inherritance mapping doesn't seem to be helping (http://docs.doctrine-project.org/en/latest/reference/inheritance-mapping.html)

I understand the error, but shouldn't it be possible to be able to have 2 entities (extending each other) write to the same database table

2

2 Answers

2
votes

Inheritance is not configured in your example. You have to set single table inheritance to do what you want :

/**
 * @Entity(name="customer")
 * @InheritanceType("SINGLE_TABLE")
 * @DiscriminatorColumn(name="discr", type="string")
 * @DiscriminatorMap({"customer1" = "Namespace\To\First\Bundle\Customer", "customer2" = "Namespace\To\Another\Bundle\Customer"})
 */
class Customer implements CustomerInterface, UserInterface
{ ... }

Then, keep your second customer class extending the first, that should work.

1
votes

Best way, as for me, is to ignore second entity at dbal level. Table will be created, and no error will appear. https://groups.google.com/forum/?fromgroups=#!topic/doctrine-user/rwWXZ7faPsA

P.S. Thanks Marco Pivetta, Alexandru Trandafir Catalin.