【问题标题】:Doctrine2 cannot make '2' one-to-many relationsDoctrine2 不能建立 '2' 一对多关系
【发布时间】:2013-02-14 01:30:18
【问题描述】:

我正在尝试创建具有以下关系的 3 个实体(项目、同意、不同意)。

  • 项目一对多同意
  • 项目一对多不同意

但只有两个关系中的一个(稍后声明)建立了。

这是我的 .yml 文件。


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

下面的代码是Doctrine2自动生成的Item.php。如您所见,它根本不包含“同意”。


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

如果我切换声明顺序(先'Disagree',后'Agree',如下图),此时Item.php只有'Agree'相关代码。


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

我的代码有什么问题?任何 cmets 都会有所帮助。

Item、Agree 和 Disagree 只是显示此问题的示例。在实际项目中,同意和不同意是完全不同的实体。所以,不建议我将它们合并成统一的实体。 :)

【问题讨论】:

    标签: doctrine-orm doctrine yaml one-to-many


    【解决方案1】:

    你很接近,你只需要将所有相同的关联映射类型放在相同的类型声明下:)

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多