与 refClass 中的属性的多对多关系

Posted

技术标签:

【中文标题】与 refClass 中的属性的多对多关系【英文标题】:Many-to-many relation with attributes in refClass 【发布时间】:2009-10-21 20:00:49 【问题描述】:

我目前正在设计一个网站,使用 symfony (1.2) 和 Doctrine 作为 ORM。

我有一个 Dinner 类、一个 Criteria 类和一个 Mark 类。

标记与晚餐和 标准,并具有私有属性, 如 DateOfMark、MarkValue 等。 Dinner 和 Criteria 可以有很多 标记(或无标记)。

当我使用 Doctrine 时,我在我的 schema.yml 中定义了这个模型,使用以下代码:

Dinner:
  columns:
    date:  type: timestamp, notnull: true 
    nb_presents:  type: integer, notnull: true 
  relations:
    Marks:
      class:    Criteria
      local:    dinner_id
      foreign:  criteria_id
      refClass: Mark

Criteria:
  columns:
    name:  type: string(50), notnull: true 
  relation:
    Marks:
      class:    Dinner
      local:    criteria_id
      foreign:  dinner_id
      refClass: Mark

Mark:
  columns:
    criteria_id:  type: integer, primary: true 
    dinner_id:  type: integer, primary: true 
    value:  type: integer, notnull: true 
  relations:
    Dinner:
      local:    dinner_id
      foreign:  id
    Criteria:
      local:    criteria_id
      foreign:  id

问题是Doctrine生成的SQL,它在Mark.dinner_id上添加了一个FOREIGN KEY CONSTRAINTDinner.id(这是正确的)AND它在Dinner.id上添加了一个FOREIGN KEY CONSTRAINTMark.dinner_id(确实不正确,因为晚餐可能有很多标记)。

问题

我错过了什么吗?我做错了类之间的这种关系吗?

谢谢。

【问题讨论】:

【参考方案1】:

您需要将关系定义为一对多关系。试试这个(注意“类型:许多”添加到晚餐和标准定义):

Dinner:
  columns:
    date:  type: timestamp, notnull: true 
    nb_presents:  type: integer, notnull: true 
  relations:
    Marks:
      class:    Criteria
      local:    dinner_id
      foreign:  criteria_id
      refClass: Mark
      type: many

Criteria:
  columns:
    name:  type: string(50), notnull: true 
 relation:
   Marks:
     class:    Dinner
     local:    criteria_id
     foreign:  dinner_id
     refClass: Mark
     type: many

Mark:
  columns:
    criteria_id:  type: integer, primary: true 
    dinner_id:  type: integer, primary: true 
    value:  type: integer, notnull: true 
  relations:
    Dinner:
      local:    dinner_id
      foreign:  id
    Criteria:
      local:    criteria_id
      foreign:  id

【讨论】:

以上是关于与 refClass 中的属性的多对多关系的主要内容,如果未能解决你的问题,请参考以下文章

与 SQLAlchemy 中不同的其他对象、自身和属性的多对多关系

核心数据:与状态的多对多关系

核心数据:获取特定对象的多对多关系中的所有实体?

EF Core 5.0 中的多对多关系是不是可以配置为仅保留一个导航属性(在一侧)?

与不同数据类型的多对多关系

教义中的多对多关系