我正在使用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。
我如何使学说自动设置外键。

我通过带有以下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标记/数据库设置有问题

最佳答案

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

请参考此link

10-06 12:42
查看更多