doctrine是否支持多对多连接表中的复合键?

时间:2017-11-03 15:07:39

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

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

我希望这些实体之间存在多对多的关系(提及),以便一个Post可能有许多提及的ChannelChannel可能会被许多人提及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

所以这种关系几乎与简单的多对多关系相同。

1 个答案:

答案 0 :(得分: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的官方文档。