如何在yaml Doctrine 2中添加约束索引

时间:2012-01-17 11:00:23

标签: doctrine-orm yaml

我在yaml中描述了两张表。

例如:

Entities\User:
  type: entity
  table: users
  id:
    id:
      type: integer
      generator:
        strategy: AUTO
  fields:
    username:
      type: string
      length: 64
  oneToMany:
    children:
      targetEntity: UserToUser
      mappedBy: parent
    parents:
     targetEntity: UserToUser
     mappedBy: child

Entities\UserToUser:
  type: entity
  table: user_to_user
  id:
    id:
      type: integer
      generator:
        strategy: AUTO
  fields:
    user_id:
      type: integer
      nullable: false
    child_id:
      type: integer
      nullable: false
  manyToOne:
    parent:
      targetEntity: User
      inversedBy: children
      joinColumn:
        name: user_id
        referencedColumnName: id
    child:
      targetEntity: User
      inversedBy: parents
      joinColumn:
        name: child_id
        referencedColumnName: id

在这种情况下一切都很好但实际上在表user_to_user的数据库中没有字段的唯一索引:user_id和child_id。 因此,有可能添加两个具有相同值的条目。

我试图添加约束

uniqueConstraints:
    child_user_idx:
      columns: child_id,user_id

或其他两种方式:

id:
    user_id:
      type: integer
    child_id:
      type: integer

  id:
    parent:
      associationKey: true
    child:
      associationKey: true

尝试结合这些选项,但结果是使用doctrine控制台验证每次都有错误,但生成的sql正是我所需要的。

其中一个例如:

他加入关联'parent'的列必须匹配源实体'Entities \ UserToUser'的所有标识符列,但是'child_id'缺失。 *关联'child'的连接列必须与源实体'Entities \ UserToUser'的所有标识符列匹配,但是'user_id'缺失。

我真的不明白我要添加什么,所以验证通过正确

2 个答案:

答案 0 :(得分:3)

使用YAML时,您可以尝试使用以下表示法:

Vendor\CategoryBundle\Entity\Category:
    type: entity
    table: category
    indexes:
        # the name of the index
        category_slug_idx:
            # Columns is an array, specify multiple columns for
            # a compound index
            columns: [ slug ]
    id:
        id:
            type: integer
            generator: { strategy: AUTO }

    fields:
        name:
            type: string
        slug:
            type: string

您可以看到您可以在索引下声明索引:node

答案 1 :(得分:1)

我认为这就是你要找的https://gist.github.com/1845982

Vendor\BlogBundle\Entity\BlogImage:
    type: entity
    table: blog_image

    # use two fields for our identifier
    id:
        blog:
            # flag as an association key 
            associationKey: true
        image:
            associationKey: true
    fields:
        caption:
            type: string

    # Specify our relationships for above
    manyToOne:
        project:
            targetEntity: Vendor\BlogBundle\Entity\Blog
            inversedBy: images

    oneToOne:
        image:
            targetEntity: Vendor\ImageBundle\Entity\Image