如何使用许多相关对象持久化一个对象

时间:2012-01-09 23:46:48

标签: php symfony doctrine-orm

我有实体BasketBasketItem

/**
 * Acme\BasketBundle\Entity\Basket
 *
 * @ORM\Entity(repositoryClass="Acme\BasketBundle\Repository\BasketRepository")
 * @ORM\Table(name="orders")
 * @ORM\HasLifecycleCallbacks()
 */
class Basket
{
  /**
   * @var integer $id
   *
   * @ORM\Column(name="id", type="integer")
   * @ORM\Id
   * @ORM\GeneratedValue(strategy="AUTO")
   */
  private $id;

  // ...

  /**
    * @ORM\OneToMany(targetEntity="BasketItem", mappedBy="order_id",cascade={"all"})
    */
  protected $items;

  // ...

  public function __construct() {
    $this->items = new ArrayCollection();
  }

  /**
   * Add item
   *
   * @param BasketItem $item
   */
  public function addItem(BasketItem $item)
  {
    $key = $this->find($item->getProduct()->getId());

    if ($key === false) {
        $this->items->add($item);
    } else {
        $this->items->get($key)->raiseQuantity($item->getQuantity());
    }
  }

  /**
   * Find an item (if present)
   *
   * @param integer $id
   * @return integer
   */
  public function find($id)
  {
    foreach ($this->items as $key => $item) {
        if ($item->getProduct()->getId() == $id)
            return $key;
    }
    return false;
  }
}


/**
 * Acme\BasketBundle\Entity\BasketItem
 *
 * @ORM\Entity
 * @ORM\Table(name="order_items")
 */
class BasketItem
{
  /**
   * @var integer $id
   *
   * @ORM\Column(name="id", type="integer")
   * @ORM\Id
   * @ORM\GeneratedValue(strategy="AUTO")
   */
  private $id;

  // ...

  /**
   * @ORM\ManyToOne(targetEntity="Basket", inversedBy="items")
   * @ORM\JoinColumn(name="order_id", referencedColumnName="id")
   */
  private $basket;

  // ...
}

现在,当我创建一个篮子并用项目填充它时,我无法将其持久保存到数据库中。

以下操作无效。

$basket = new Basket();
$basket->addItem(new BasketItem($product1, 1));
$basket->addItem(new BasketItem($product2, 2));

$em->persist($basket);
$em->flush();

然后我尝试更紧密地关注manual

$basket = new Basket();
$basket->addItem(new BasketItem($product1, 1));
$basket->addItem(new BasketItem($product2, 2));

$em->persist($basket);
foreach ($basket->getItems() as $item) {
    $em->persist($item);
}
$em->flush();

这没有按预期工作。

在这两种情况下,所有数据都会保存到数据库篮子项与篮子无关,即order_id实体的BasketItem为{{1 }}

有谁能解释一下我做错了什么,拜托?请注意我是Doctrine的新手。谢谢!




修改

我真的很困惑。这是我的简化测试:

NULL


<?php

namespace Amsel\BasketBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * Amsel\BasketBundle\Entity\Basket
 *
 * @ORM\Entity(repositoryClass="Amsel\BasketBundle\Repository\BasketRepository")
 * @ORM\Table(name="orders")
 */
class Basket
{
    /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var ArrayCollection $items
     *
     * @ORM\OneToMany(targetEntity="BasketItem", mappedBy="basket", cascade={"all"})
     */
    protected $items;

    public function __construct() {
        $this->items = new ArrayCollection();
    }

    /**
     * Add item
     *
     * @param BasketItem $item
     */
    public function addItem(BasketItem $item)
    {
        $this->items->add($item);
    }

    /**
     * Get id
     *
     * @return integer 
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Get items
     *
     * @return Doctrine\Common\Collections\Collection 
     */
    public function getItems()
    {
        return $this->items;
    }
}


<?php

namespace Amsel\BasketBundle\Entity;

use Doctrine\ORM\Mapping as ORM;


/**
 * Amsel\BasketBundle\Entity\BasketItem
 *
 * @ORM\Entity(repositoryClass="Amsel\BasketBundle\Repository\BasketItemRepository")
 * @ORM\Table(name="order_items")
 */
class BasketItem
{
    /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var Basket $basket
     *
     * @ORM\ManyToOne(targetEntity="Basket", inversedBy="items")
     * @ORM\JoinColumn(name="order_id", referencedColumnName="id")
     */
    protected $basket;


    /**
     * Get id
     *
     * @return integer 
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set basket
     *
     * @param Amsel\BasketBundle\Entity\Basket $basket
     */
    public function setBasket(\Amsel\BasketBundle\Entity\Basket $basket)
    {
        $this->basket = $basket;
    }

    /**
     * Get basket
     *
     * @return Amsel\BasketBundle\Entity\Basket 
     */
    public function getBasket()
    {
        return $this->basket;
    }
}

但仍然 - 订单商品(public function testAction(Request $request) { $em = $this->getDoctrine()->getEntityManager(); $basket = new Basket(); $basket->addItem(new BasketItem()); $basket->addItem(new BasketItem()); $em->persist($basket); try { $em->flush(); } catch(Exception $e) { die('ERROR: '.$e->getMessage()); } die ('end'); } )已存储但与订单相关联(BasketItem)。

3 个答案:

答案 0 :(得分:3)

您的注释映射在您的Basket实体中是错误的:“mappedBy”属性必须引用实体字段,而不是数据库列。

/**  
 * @ORM\OneToMany(targetEntity="BasketItem", mappedBy="basket",cascade={"all"})  
 */  
 protected $items;

答案 1 :(得分:3)

如果我正确理解了系统,我还必须 - 因为它是双向关系 - 手动将父Basket实体分配给每个BasketItem实体。

public function testAction(Request $request) {

    $em = $this->getDoctrine()->getEntityManager();

    $basket = new Basket();

    $bi1 = new BasketItem();
    $bi1->setBasket($basket);

    $bi2 = new BasketItem();
    $bi2->setBasket($basket);

    $basket->addItem($bi1);
    $basket->addItem($bi2);

    $em->persist($basket);

    try {
        $em->flush();
    } catch(Exception $e) {
        die('ERROR: '.$e->getMessage());
    }        
    die ('end');
}

这样做很好但是如果我走错路,请纠正我。

感谢所有花时间看我问题的人!

答案 2 :(得分:1)

我是Symfony和Doctrine的新人,但这很奇怪。我认为它应该双向工作,但似乎你必须在BasketItem上设置Basket

$bi->setBasket($basket);

如果你想让它以两种方式运作,例如:

$basket->addItem($bi);

你必须修改你的addItem方法和removeItem方法

/**
 * Add item
 *
 * @param BasketItem $item
 */
public function addItem(BasketItem $item)
{
    $item->setBasket($this);
    $this->items->add($item);
}

/**
 * Remove item
 *
 * @param BasketItem $item
 */
public function removeItem(BasketItem $item)
{
    $item->setBasket(null);
    $this->items->removeElement($item);
}

[编辑]看看:http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/association-mapping.html#owning-and-inverse-side-on-a-manytomany-association