1

我在两个实体之间建立双向一对一关系时遇到问题。我有一个可以引用另一个实体“DonationData”的实体“Campaign”。创建的捐赠数据始终与活动相关联。我想要一个双向关系,因为我希望能够从 DonationData 实体中找到相关的活动。

这是我的活动实体代码:

<?php
/**
 * @ORM\Entity
 * ...
 */
class Campaign
{
...
/**
 * @ORM\OneToOne(targetEntity="DonationData", mappedBy="campaign", cascade={"persist", "remove"})
 */
protected $donationData;

...

/**
 * Set donationData
 *
 * @param DonationData $donationData
 * @return Campaign
 */
public function setDonationData(DonationData $donationData = null)
{
    $this->donationData = $donationData;

    return $this;
}

...

?>

以及我的 DonationData 实体的相关代码:

<?php
/**
 * @ORM\Entity
 * ...
 */
class DonationData
{
...
/**
 * @ORM\OneToOne(targetEntity="Campaign")
 * @ORM\JoinColumns({
 *     @ORM\JoinColumn(name="campaign_id", referencedColumnName="id")
 * })
 */
protected $campaign;

...

/**
 * Set campaign
 * @param Campaign $campaign
 *
 * @return DonationData
 */
public function setCampaign($campaign)
{
    $this->campaign = $campaign;

    return $this;
}


...
?>

我在我的活动表单 (CampaignType.php) 中添加我的 DonationData 表单的一段代码

<?php
...
->add('donationData', new DonationDataType(), array(
    'label' => false
))
...
?>

And in the CampaignController.php side, when I'm handling the creation operations, I didn't change anything : I'm just persisting the related entity binded from the request, and then flushing the Entity Manager :

<?php
...
$em->persist($campaign);
$em->flush();
...
?>

My problem is when I want to persist a Campaign entity form that has an embedded DonationData form inside. I successfully persist both the Campaign and the DonationData entities, but there is only the donation_data_id reference in the Campaign entry that is persisted. When I look in database to the persisted DonationData, the campaign_id is always set to NULL.

Do you see any explanation for that?

Thank you.

4

1 回答 1

1

In class DonationData, field $campaign you don't specify the inversedBy property, should be

@ORM\JoinColumn(name="campaign_id", referencedColumnName="id", inversedBy="donationData")

and did you set the cascade_validation default option in the parent form?

as in http://symfony.com/doc/current/reference/forms/types/form.html

于 2013-10-11T21:18:14.303 回答