Symfony2将一个新实体链接到一个现有实体,而不需要编辑现有实体


Symfony2 link a new Entity to an existing Entity without editing the existing Entity

我有一个叫EC-cube的应用程序运行在Symfony 2.7.9之上。

我的任务是添加"功能"到该应用程序,但触摸现有代码。
我能做的是创建新的元素(实体,控制器)或通过提供的一些事件挂钩到它们。

我想做的是向现有实体添加一些字段。为此,我创建了一个实体来包含新数据,它通过主键映射到原始实体=>我有2个表。

我做了什么

我设法通过"钩子"来显示表单中的新字段,方法是将我的表单类型添加到我在事件方法中作为参数接收的原始formBuilder中。

工作很棒,一个表单被发送,我有另一个事件设置接收表单数据和更新/保存我的实体。

更多上下文

现有实体:客户

扩展实体:MyCustomer

New Entity: UserCustom(其中添加了新字段)。

这里是实体:

class MyCustomer extends Customer {
    // no changes, I just want a new name to use the regarding YML file to add a relation
}
class UserCustom extends 'Eccube'Entity'AbstractEntity {
    private $id;
    private $dog_name;
    // other things and setters/getters
    // ...
}

cdm.yml文件

扩展现有客户实体:

Plugin'UserCustom'Entity'MyCustomer:
type: entity
table: dtb_customer # that table already exists
# I removed all columns definition in that file and just customized the repo and added the relation I want
repositoryClass: Plugin'UserCustom'Repository'MyCustomerRepository
oneToOne:
    Details:
        targetEntity: Plugin'UserCustom'Entity'UserCustom
        joinColumn:
            name: customer_id
            referencedColumnName: customer_id

一对一的关系是这里的临界点。

对于新数据:

Plugin'UserCustom'Entity'UserCustom:
type: entity
table: plg_user_custom
repositoryClass: Plugin'UserCustom'Repository'UserCustomRepository
id:
    id:
        type: integer
        nullable: false
        unsigned: false
        id: true
        column: customer_id
        generator:
            strategy: NONE
fields:
    dog_name:
        type: text
        nullable: true
    mailmaga:
        type: integer
        nullable: true
lifecycleCallbacks: {  }

然后我可以用MyCustomer覆盖ple中的Customer实体,并向与其相关的存储库(MyCustomerRepository)添加一些逻辑。

什么不工作

嗯,逻辑是我想要的工作,但我不能迁移(迁移:diff等…),因为表dtb_customer存在2个实体:CustomerMyCustomer

我该怎么办呢?最简单的想法是使现有的表被迁移忽略。

现在我用手工编辑表格,但这很容易出错,我认为这不好。


我不是Symfony的大师,这对我来说似乎是压倒性的,因此我的问题可能听起来很容易甚至不相关…

您可以通过yml或注释进行映射。所以你不需要两者都需要。

那么行$app['eccube.repository.customer']->getQueryBuilderBySearchData($searchData);似乎是一个丘疹容器。不是交响乐DIC。

要解决这个问题,你应该尝试在需要的地方用定制连接扩展原始的存储库类,并将该类注入$app['eccube.repository.customer']。这意味着,您将不会触及控制器代码。只需重写getQueryBuilderBySearchData()方法。