【问题标题】:Why does Doctrine create an index on only one column in the linking table?为什么 Doctrine 只在链接表的一列上创建索引?
【发布时间】:2026-02-06 12:45:02
【问题描述】:

就像*一样,Question和Tag之间是多对多的关系。

运行这些 symfony 命令后:

./symfony doctrine:drop-db
./symfony doctrine:build-db
./symfony doctrine:build-model
./symfony doctrine:build-sql
./symfony doctrine:insert-sql

使用以下架构:

schema.yml

Tag:
 columns:
   name:
     type: string(10)
     notnull: true
 relations:
     Questions:
       class: Question
       foreignAlias: Tags
       refClass: QuestionTag

Question:
  columns:
    html:
     type: string(1000)
  relations:
     Tags:
       class: Tag
       foreignAlias: Questions
       refClass: QuestionTag

QuestionTag:
  columns:
    question_id:
     type: integer     
     primary: true
    tag_id:
      type: integer      
      primary: true
  relations:
    Question:
      class: Question
      foreignAlias: QuestionTags
      type: many
      foreignType: one
    Tag:
      class: Tag
      foreignAlias: QuestionTags
      type: many
      foreignType: one

QuestionTag 链接表中,这有助于建立TagQuestion 表之间的多对多关系,我发现Doctrine 只在tag_id 列上创建了一个“正常”索引。为什么在这个专栏上而不是在question_id 专栏上?我不知道。

我认为这很奇怪,因为 Doctrine 创建的索引应该在两个 question_idtag_id 列上,因此它应该成为“唯一”索引,而不是“正常的'一,因为question_idtag_id一起构成复合主键。

我的理解正确吗? 如果是,为什么 Doctrine 没有以正确的方式做到这一点?

【问题讨论】:

  • 为什么不手动定义 PK 和索引?

标签: database database-design symfony1 doctrine


【解决方案1】:

我相信 Doctrine 不支持复合主(或外)键。请记住,Doctrine 项目进展非常迅速,但它还很年轻。新功能一直在添加,但我不认为 1.x 分支计划使用多列键。

解决方法是创建一个唯一的主键列 question_tag_id,作为 QuestionTag 表中的 3 个字段之一。

【讨论】:

    【解决方案2】:

    如果我正确阅读了您的代码,您不应在 QuestionTag 表中再次定义关系。

    也可以手动为两列创建索引(只需在您的架构中定义它),虽然我还没有看到如何在 Doctrine 中对两列应用唯一约束。

    【讨论】: