Splitting a ManyToMany association into 2 pairs of

2019-09-02 18:32发布

问题:

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).

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);

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!

回答1:

You have your answer in your question :

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