Doctrine2 cannot make '2' one-to-many relations

旧城冷巷雨未停 提交于 2019-12-11 12:25:57

问题


I'm trying to make 3 entities (Item, Agree, Disagree) with following relations.

  • Item one-to-many Agree
  • Item one-to-many Disagree

But only one relation (declared later) out of two has made.

Here're my .yml files.


Entities\Item:
  type: entity
  fields:
    id:
      type: integer
      id: true
      generator:
        strategy: AUTO
  oneToMany:
    agrees:
      targetEntity: Agree
      mappedBy: items
  oneToMany:
    disagrees:
      targetEntity: Disagree
      mappedBy: items

Entities\Agree:
  type: entity
  fields:
    id:
      type: integer
      id: true
      generator:
        strategy: AUTO
  manyToOne:
    items:
      targetEntity: Item
      inversedBy: agrees

Entities\Disagree:
  type: entity
  fields:
    id:
      type: integer
      id: true
      generator:
        strategy: AUTO
  manyToOne:
    items:
      targetEntity: Item
      inversedBy: disagrees

And the code below is the Item.php auto-generated by Doctrine2. As you can see, it doesn't contains 'Agree' at all.


namespace Entities;

class Item {
    private $id;
    private $disagrees;

    public function __construct() {
        $this->disagrees = new \Doctrine\Common\Collections\ArrayCollection();
    }

    public function getId() {
        return $this->id;
    }

    public function addDisagrees(\Entities\Disagree $disagrees) {
        $this->disagrees[] = $disagrees;
    }

    public function getDisagrees() {
        return $this->disagrees;
    }
}

If I switches the declaration order ('Disagree' first, followed by'Agree', like the below), Item.php has only 'Agree'-related code in this time.


Entities\Item:
  type: entity
  fields:
    id:
      type: integer
      id: true
      generator:
        strategy: AUTO
  oneToMany:
    disagrees:
      targetEntity: Disagree
      mappedBy: items
  oneToMany:
    agrees:
      targetEntity: Agree
      mappedBy: items

What's wrong with my code? Any comments will be helpful.

Item, Agree and Disagree are just samples to show this problem. In real project, Agree and Disagrees are totally different entity. So, don't suggest me to merge them into unified entity. :)


回答1:


You were close, you just need to put all same association mapping types under the same type declaration :)

  oneToMany:
    agrees:
      targetEntity: Agree
      mappedBy: items  
    disagrees:
      targetEntity: Disagree
      mappedBy: items


来源:https://stackoverflow.com/questions/7818097/doctrine2-cannot-make-2-one-to-many-relations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!