【问题标题】:Doctrine2 Symfony2 extending entity in different bundle but with same database table nameDoctrine2 Symfony2 在不同的包中扩展实体但具有相同的数据库表名
【发布时间】:2025-12-10 08:05:01
【问题描述】:

我在 symfony2 中扩展具有相同数据库表名的实体时遇到问题。 我正在尝试在 symfony 中扩展一个实体,但基础实体需要可重用,所以它不会总是被扩展。

这是我目前拥有的简化示例。 我的客户实体:

namespace Bundle\Entity\Customer;

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

扩展实体(在另一个包中):

namespace AnotherBundle\Entity\Customer;

use Bundle\Entity\Customer\Customer as BaseCustomer;

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

客户界面:

namespace Bundle\Model\Customer;

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

在我的 config.yml 我有以下规则:

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

生成 SQL 时出现以下错误:

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

我需要第二个实体来扩展第一个(基本)实体并维护数据库表名。但是当我不扩展第一个(基础)实体时,我仍然希望这个实体能够独立工作。

我已经尝试过这个来源,但他们无法解决我的问题: Creating portable Bundles with extendable entities in Symfony2(没用,虽然实体确实映射到了正确的,但它仍然给了我重复的表名错误)

此外,学说的继承映射似乎没有帮助 (http://docs.doctrine-project.org/en/latest/reference/inheritance-mapping.html)

我理解错误,但是否应该能够让 2 个实体(相互扩展)写入同一个数据库表

【问题讨论】:

    标签: symfony doctrine-orm


    【解决方案1】:

    您的示例中未配置继承。你必须设置single table inheritance 做你想做的事:

    /**
     * @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
    { ... }
    

    然后,让你的第二个客户类扩展第一个,这应该可以工作。

    【讨论】:

    • 问题是它在我的客户表中创建了一个额外的字段,这在我的情况下是无用的。我希望有一种方法可以使它成为没有额外鉴别器字段的单表,但它确实以这种方式工作。谢谢!
    【解决方案2】:

    就我而言,最好的方法是忽略 dbal 级别的第二个实体。将创建表, 并且不会出现错误。 https://groups.google.com/forum/?fromgroups=#!topic/doctrine-user/rwWXZ7faPsA

    附:感谢 Marco Pivetta、Alexandru Trandafir Catalin。

    【讨论】: