将ManyToMany关联分为2对OneToMany/ManyToOne(原则) [英] Splitting a ManyToMany association into 2 pairs of OneToMany/ManyToOne (Doctrine)
问题描述
我将通过示例展示案例(将会更加清楚): 我有"Groupies"(因为组是保留名称),并且我有公司".一个Groupie可能会选择几家公司,而同一公司则相反(通常是ManyToMany关联).
I'll expose the case with the example (it'll be clearer): I have 'Groupies' (since group is a reserved name) and I have Companies. A Groupie may choose several Companies, and the same aplies in reverse (typical ManyToMany asociation).
问题是:我需要保留一些特定于关联本身的其他数据(我们称其为选择").因此,ManyToMany被两对OneToMany/ManyToOne关联所取代,现在每个选择"只有一个"Groupie"和一个公司.每个类的学说元数据是:
The thing is: I need to persist some additional data wich are specific of the association itself (let's call it 'Choice'). So, the ManyToMany is replaced by two pairs of OneToMany/ManyToOne asociations, and now each 'choice' has only one 'groupie' and one company. The doctrine metadata for each class are:
Company.orm.yml:
Acme\AppBundle\Entity\Company:
type: entity
#fields...
oneToMany:
choices:
targetEntity: Acme\AppBundle\Entity\Choice
mappedBy: company
Groupie.orm.yml:
Acme\AppBundle\Entity\Groupie:
type: entity
#fields...
oneToMany:
choices:
targetEntity: Acme\AppBundle\Entity\Choice
mappedBy: groupie
Choice.orm.yml:
Acme\AppBundle\Entity\Choice:
type: entity
#fields...
manyToOne:
company:
targetEntity: Acme\AppBundle\Entity\Company
inversedBy: choices
manyToOne:
groupie:
targetEntity: Acme\AppBundle\Entity\Groupie
inversedBy: choices
问题是,当我运行命令时:
The problem is, when I run the comand:
php app/console doctrine:schema:update --dump-sql
似乎只能识别两种关系(追星族)之一:
only seems to recognize one of the two relationships (groupies):
CREATE TABLE choice (id INT AUTO_INCREMENT NOT NULL, groupie_id INT DEFAULT NULL, creationDate DATE NOT NULL, orderNumber SMALLINT NOT NULL, numberOfAccounts SMALLINT NOT NULL, INDEX IDX_43CA0AD68D0C5D40 (choice_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB;
ALTER TABLE choice ADD CONSTRAINT FK_43CA0AD68D0C5D40 FOREIGN KEY (groupie_id) REFERENCES groupie (id);
我当然做错了,但是我找不到如何将ManyToMany分成两对详细的OneToMany/ManyToOne关联的方法.这样,似乎Choice.orm.yml中的最后一个"manyToOne"元数据将覆盖前一个元数据.实际上,如果我先编写分组"manyToOne",然后再编写公司的分组,那么最后一个(公司)是选择表中唯一的外键!
I'm certainly doing something wrong, but I couldn't find how to split a ManyToMany into two pairs of OneToMany/ManyToOne associations in detail. This way, it seems the last 'manyToOne' metadata in Choice.orm.yml overwrites the previous. In fact, if I write first the groupie 'manyToOne' and then the company's, then this last one (company) is the only foreign key in the choice table!
推荐答案
您的问题有答案:
将相同类型的所有关联归入相同的缩进级别.
Group all associations of same type under the same indentation level.
Acme\AppBundle\Entity\Choice:
type: entity
#fields...
manyToOne:
company:
targetEntity: Acme\AppBundle\Entity\Company
inversedBy: choices
groupie:
targetEntity: Acme\AppBundle\Entity\Groupie
inversedBy: choices
这篇关于将ManyToMany关联分为2对OneToMany/ManyToOne(原则)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!