添加相关实体时,Doctrine对象不设置外键

时间:2013-09-20 14:18:49

标签: mysql orm doctrine yaml entity-relationship

我在CodeIgniter 2中使用Doctrine 2,基本上我想实现这样的目标:

 $product = $this->doctrine->em->find("Entities\Product", 1)
 $feature = new Entities\Feature;
 $feature->setName("foo");

 $product->addFeature($feature);

 $this->doctrine->em->persist($product);
 $this->doctrine->em->flush();

当持久化要素对象添加到数据库但将product_id设置为null时。 如何让doctrine自动设置外键。

我通过带有以下YAML标记的doctrine命令行工具创建我的类和表格

Entities\Product:
  type: entity
  table: products
  id:
    id:
      type: integer
      generator:
        strategy: AUTO
  fields:
    name:
      type: string
      length: 50
  oneToMany:
    features:
      targetEntity: Feature
      mappedBy: product
      cascade: ["persist"]



Entities\Feature:
  type: entity
  table: features
  id:
    id:
      type: integer
      generator:
        strategy: AUTO
  fields:
    name:
      type: string
      length: 50
  manyToOne:
    product:
      targetEntity: Product
      inversedBy: features
      joinColumn:
        name: product_id
        referencedColumnName: id

编辑:

当然我可以通过更改Product.php中的addFeature方法来解决问题

public function addFeature(\Entities\Feature $features)
{
       $features->setProduct($this);
       $this->features[] = $features;
       return $this;
}

但是因为这应该可以在不触及代码的情况下工作,我猜我的YAML标记/数据库设置有问题

1 个答案:

答案 0 :(得分:0)

“在多对一关系中,默认情况下,多方是拥有方,因为它拥有外键。”

请参阅此link