使用Symfony2 / Doctrine2进行简单的一对一设置和主要操作

时间:2013-09-18 23:50:38

标签: php mysql symfony doctrine-orm doctrine

我对这一切感到困惑。

我认为Doctrine不允许你在连接上使用主键(我在某处读取它),但我在这里http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/limitations-and-known-issues.html看到它说“不可能使用指向非连接的连接列-primary keys“看起来恰恰相反。

无论如何,我想加入主键,所以我肯定可以这样做吗?我试图建立一个简单的一对一关系。这就是我所拥有的,但是我遇到了各种错误,指出了这个问题。

我可以通过加入不是主键的字段来设置它,但在我想要使用它的情况下,这似乎是垃圾。

我只是想要一个额外的数据库表来扩展主数据库表。基于任何限制,最好的方法是什么?

我正在使用Doctrine 2.2,但可以使用任何版本。

下面的代码是我期望的工作,但它不允许它。

-

用户:

user_id # primary
field_1
field_2

额外用户信息:

extra_id # primary
extra_info_1
extra_info_2

User.orm.yml:

User:
    type: entity
    table: null
    fields:
        user_id:
            id: true
            generator:
                strategy: AUTO
        field_1:
            type: string
        field_2:
            type: string

    oneToOne:
        user_id:
            targetEntity: UserExtra
            mappedBy: extra_id

UserExtra.orm.yml:

UserExtra:
    type: entity
    table: null
    fields:
        extra_id:
            id: true
            generator:
                strategy: AUTO
        extra_info_1:
            type: string
        extra_info_2:
            type: string

    oneToOne:
        extra_id:
            targetEntity: User
            mappedBy: user_id

1 个答案:

答案 0 :(得分:1)

您的架构不正确。该ID应位于不在id下的fields密钥下,您永远不应在实体中编写somethig_id。您可以通过引用而不是数据库ID将对象绑定在一起。请仔细阅读文档。 自Doctrine 2.1以来,可以使用主键作为相关实体中的外键; identity-through-foreign-entities

User:
  type: entity
  id:
    id:
      type: integer
      generator:
        strategy: AUTO

Address:
  type: entity
  id:
    user:
      associationKey: true
  oneToOne:
    user:
      targetEntity: User