【问题标题】:Doctrine object not setting foreig key when adding related entity添加相关实体时,Doctrine 对象未设置外键
【发布时间】:2013-09-20 14:18:49
【问题描述】:

我将 Doctrine 2 与 CodeIgniter 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 设置为空。 如何让教义自动设置外键。

我使用以下 YAML 标记通过教义命令行工具创建我的类和表

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 标记/数据库设置有问题

【问题讨论】:

    标签: mysql orm doctrine yaml entity-relationship


    【解决方案1】:

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

    请参考link

    【讨论】:

    • 是的。我的问题是它没有默认保存外键,因为它没有被设置。
    • 一般情况下,Product 与特征之间可能存在多对一的多对多关系。如果您的产品最多只有一个功能,而其他产品可能具有相同的功能,那么它与功能是多对一的关系。如果你的产品会有很多功能,而另一个产品可以共享该功能,那么它与功能是多对多的关系。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 2012-04-26
    • 1970-01-01
    相关资源
    最近更新 更多