【问题标题】:Does doctrine support composite keys in many-to-many join tables?学说是否支持多对多连接表中的复合键?
【发布时间】:2018-04-16 08:50:24
【问题描述】:

我有实体 ChannelPostChannel 具有简单整数 idPost 具有由自己的 idchannel_id 组成的复合键。

我想在这些实体之间建立多对多关系(提及),这样一个Post 可能会提到很多Channels,而Channel 可能会被很多Posts 提及。

问题是 - 如果 Doctrine 支持,我该如何实现这种关系?

Domain\Telegram\Models\Channel:
  type: entity
  id:
    id:
      type: integer

  fields:
    name:
      type: string
      nullable: true

  oneToMany:
    posts:
      targetEntity: Domain\Telegram\Models\Post
      mappedBy: channel


Domain\Telegram\Models\Post:
  type: entity
  id:
    channel:
      associationKey: true
    id:
      type: integer

  manyToOne:
    channel:
      targetEntity: Domain\Telegram\Models\Channel
      inversedBy: posts

更新和解决方案

@WilliamPerron 的解决方案几乎奏效了。如果在当前状态下使用,doctrine:schema:validate 会返回错误:

[Mapping] FAIL - 实体类 'Domain\Telegram\Models\Channel' 映射无效:

多对多表“提及”的反向连接列必须包含目标实体的所有标识符列 'Domain\Telegram\Models\Post',但缺少 'channel_id'。

inverseJoinColumns 部分应如下所示:

    inverseJoinColumns:
      post_id:
        referencedColumnName: id
      post_channel_id:
        referencedColumnName: channel_id

所以这种关系实际上与简单的多对多关系相同。

【问题讨论】:

    标签: php symfony doctrine-orm composite-primary-key


    【解决方案1】:

    是的,这是可能的

    您只需使用groups 元素指定它连接到哪个表,然后指定它映射到的实体。对于单向关系,模式如下所示:

    Channel:
      type: entity
      manyToMany:
        posts:
          targetEntity: Post
          joinTable:
            name: posts_channels
            joinColumns:
              channel_id:
                referencedColumnName: id
            inverseJoinColumns:
              post:
                referencedColumnName: id
    

    对于双向关系,您需要添加 inversedBy 元素:

    Channel:
      type: entity
      manyToMany:
        posts:
          targetEntity: Post
          inversedBy: channels
          joinTable:
            name: posts_channels
            joinColumns:
              channel_id:
                referencedColumnName: id
            inverseJoinColumns:
              post_id:
                referencedColumnName: id
    
    Post:
      type: entity
      manyToMany:
        channels:
          targetEntity: Channel
          mappedBy: posts
    

    可以在here找到官方文档。

    【讨论】:

    • 您确定您的答案适用于复合键的情况吗? AFAIK 你的代码没有表现出任何意识。
    • @svgrafov Doctrine 的多对多关系的优点是它会正确映射 ID,并在 ArrayCollection 中返回所有关联记录,因此无需完全使用复合键
    • 您能否更新您的代码(特别是joinColumns 部分)以更接近我的情况?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-20
    • 1970-01-01
    相关资源
    最近更新 更多