gpt4 book ai didi

php - doctrine2 : in a one-to-many bidirectional relationship, 如何从反面保存?

转载 作者:可可西里 更新时间:2023-11-01 13:45:43 24 4
gpt4 key购买 nike

我有下面的一对多双向关系。

在使用 symfony2 任务生成 crud 操作后,当我尝试在新建/编辑类别表单中保存与类别关联的产品时,产品未保存...

namespace Prueba\FrontendBundle\Entity;

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

/**
* @ORM\Entity
* @ORM\Table(name="category")
*/
class Category
{

/**
* @var integer $id
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;

/**
* @ORM\OneToMany(targetEntity="Product", mappedBy="category")
*/
protected $products;

/**
* @ORM\Column(name="name")
*/
protected $name;

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

public function getId()
{
return $this->id;
}

public function getName()
{
return $this->name;
}

public function setName($name)
{
$this->name = $name;
}

public function __toString()
{
return $this->name;
}

public function getProducts()
{
return $this->products;
}

public function setProducts($products)
{
die("fasdf"); //here is not entering
$this->products[] = $products;
}

public function addProduct($product)
{
die("rwerwe"); //here is not entering
$this->products[] = $product;
}
}
namespace Prueba\FrontendBundle\Entity;

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

/**
* @ORM\Entity
* @ORM\Table(name="product")
*/
class Product
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;

/**
* @ORM\ManyToOne(targetEntity="Category", inversedBy="products")
* @ORM\JoinColumn(name="category_id", referencedColumnName="id")
*/
protected $category;

/**
* @ORM\Column(type="string", length=100)
*/
protected $name;


public function getId()
{
return $this->id;
}

public function getName()
{
return $this->name;
}

public function setName($name)
{
$this->name = $name;
}

public function getCategory()
{
return $this->category;
}

public function setCategory($category)
{
$this->category = $category;
}

public function __toString()
{
return $this->name;
}
}

最佳答案

由于它是双向的,您需要更新双方的关联。

将此函数添加到类别实体中(您可以将其称为 addChild,如果您愿意):

public function addProduct($product)
{
$this->children->add($product);
}

然后同时更新两个关联:

public function setProductCategory($product_category)
{
$this->productCategory = $product_category;
$product_category->addProduct($this);
}

提示:不要使用 $children/$parent 来描述实体。称它为 $category/$product,当你想添加另一个“父”关系时,你会遇到问题。

关于php - doctrine2 : in a one-to-many bidirectional relationship, 如何从反面保存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10618514/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com