Doctrine似乎为OneToOne生成并保存外键值,但不适用于OneToMany

时间:2017-05-09 22:35:52

标签: php symfony doctrine-orm doctrine

当我保存具有各种关联的复合Doctrine实体时,Doctrine似乎为OneToOne关系保存外键,但不保存OneToMany。我不明白它是如何以及为什么这样做的。

以下是一些代码:

 /** @Entity */
class SelectionForm
{

    /**
     * @Id @Column(type="integer")
     * @GeneratedValue
     */
    private $id;

    /**
     * @OneToOne(targetEntity="MotorFieldset", cascade={"persist", "remove"})
     *
     * @var MotorFieldset
     */
    protected $motor;

    /**
     * @OneToMany(targetEntity="CasePoint", mappedBy="selectionForm", cascade={"persist", "remove"})
     *
     * @var CasePoint[]
     */
    protected $casePoints;
}

 /** @Entity */
class CasePoint
{

    /**
     * @Id @Column(type="integer")
     * @GeneratedValue
     */
    private $id;

    /**
     * @ManyToOne(targetEntity="SelectionForm", inversedBy="casePoints", cascade={"persist", "remove"})
     *
     * @var SelectionForm
     */
    private $selectionForm;

     /** @Column(type="float") */
    private $flow;
}

/** @Entity */
class MotorFieldset
{

    /**
     * @Id @Column(type="integer")
     * @GeneratedValue
     */
    private $id;

    /**
     * @Column(type="integer")
     */
    private $voltage;
}

当我使用值和4个CasePoint记录填充上述SelectionForm对象,然后执行persist()flush()时,我看到如下内容:

INSERT INTO MotorFieldset (voltage) VALUES ('380')
INSERT INTO SelectionForm (motor_id) VALUES (9)
INSERT INTO CasePoint (flow, selectionForm_id) VALUES ('140', NULL)
INSERT INTO CasePoint (flow, selectionForm_id) VALUES ('140', NULL)
INSERT INTO CasePoint (flow, selectionForm_id) VALUES ('140', NULL)
INSERT INTO CasePoint (flow, selectionForm_id) VALUES ('140', NULL)

我觉得非常有趣的是,上面的第二行,motor_id的外键,等于9,以某种方式由Doctrine插入,尽管它只是在第1行中创建。 。 但selectionForm_id未插入CasePoint记录,并设置为NULL。

为什么Doctrine正确地为OneToOne生成外键但不为OneToMany生成外键?

Doctrine如何知道为OneToOne正确生成外键值?

1 个答案:

答案 0 :(得分:1)

确保你做的事情如下:

$selectionForm->getCasePoints()->add($casePoint);
$casePoint->setSelectionForm($selectionForm);

为了避免这种类型的问题很常见,在实体中添加一个方法来执行此操作:

SelectionForm.php

function addCasePoint(CasePoint $casePoint){
    $this->getCasePoints()->add($casePoint);
    $casePoint->setSelectionForm($this);
}