同桌上的多对多关系

时间:2010-06-23 12:24:40

标签: symfony1 doctrine entity-relationship

我正试图在'Gabarits'之间建立一个m2m关系。

  • 一个gabarit可以有很多Gabarits(称为选项)
  • 一个gabarit可以来自许多Gabarits(称为OptionsFrom)

这是我的schema.yml:

Gabarit:
  actAs: [Attachable]
  columns:
    libelle: { type: string, size: 255 }
    description: { type: clob }
  relations:
    Options:
      class: Gabarit
      refClass: Gabarit2Gabarit
      local: gabarit_id
      foreign: fils_id
      foreignAlias: OptionsFrom

Gabarit2Gabarit:
  columns:
    fils_id: { type: integer, primary: true }
    gabarit_id: { type: integer, primary: true }
  relations:
    Gabarit:
      class: Gabarit
      local: gabarit_id
      alias: Gabarit
      foreignAlias: Gabarit2Gabarits
    Fils:
      class: Gabarit
      local: fils_id
      alias: Fils
      foreignAlias: Gabarit2Gabarits

生成的代码是:

   $this->hasMany('Gabarit as Options', array(
         'refClass' => 'Gabarit2Gabarit',
         'local' => 'gabarit_id',
         'foreign' => 'fils_id'));

    $this->hasMany('Gabarit as OptionsFrom', array(
         'refClass' => 'Gabarit2Gabarit',
         'local' => 'fils_id',
         'foreign' => 'gabarit_id'));

根据http://www.doctrine-project.org/projects/orm/1.2/docs/manual/defining-models/en#relationships:join-table-associations:self-referencing-nest-relations:non-equal-nest-relations

,这似乎很好

逻辑上,它会给我这个:

foreach($gabarit_>getOptions() as $option)
{
    in_array($gabarit->getId(), $options->getOptionsFrom()->getPrimaryKeys()); // should be true but returns false !!
}

为getOptions()生成SQL:

SELECT gabarit.id AS gabarit__id, gabarit.libelle AS gabarit__libelle, gabarit.description AS gabarit__description, gabarit2_gabarit.fils_id AS gabarit2_gabarit__fils_id, gabarit2_gabarit.gabarit_id AS gabarit2_gabarit__gabarit_id FROM gabarit INNER JOIN gabarit2_gabarit ON gabarit.id = gabarit2_gabarit.fils_id WHERE gabarit.id IN (SELECT fils_id FROM gabarit2_gabarit WHERE gabarit_id = '507') ORDER BY gabarit.id ASC

为getOptionsFrom()生成SQL:

SELECT gabarit.id AS gabarit__id, gabarit.libelle AS gabarit__libelle, gabarit.description AS gabarit__description, gabarit2_gabarit.fils_id AS gabarit2_gabarit__fils_id, gabarit2_gabarit.gabarit_id AS gabarit2_gabarit__gabarit_id FROM gabarit INNER JOIN gabarit2_gabarit ON gabarit.id = gabarit2_gabarit.gabarit_id WHERE gabarit.id IN (SELECT gabarit_id FROM gabarit2_gabarit WHERE fils_id = '529') ORDER BY gabarit.id ASC

你知道为什么Gabarit :: getOptionsFrom会返回一个空集合吗?

提前谢谢, 弗洛里安。

1 个答案:

答案 0 :(得分:1)

很可能是你使用相同的别名

foreignAlias:Gabarit2Gabarits

你的Gabarit2Gabarit应该是这样的:

Gabarit2Gabarit:
  columns:
    fils_id: { type: integer, primary: true }
    gabarit_id: { type: integer, primary: true }
  relations:
    Gabarit:
      class: Gabarit
      local: gabarit_id
      alias: Gabarit
      foreignAlias: Gabarit2GabaritsGabarit
    Fils:
      class: Gabarit
      local: fils_id
      alias: Fils
      foreignAlias: Gabarit2GabaritsFils

这可能会有所帮助吗?