Doctrine2: in a one-to-many bidirectional relationship, how to keep the other side?

I have a one-to-many bidirectional relationship below.

After generating crud actions with symfony2 task, when I try to save Products associated with a category in a new / editable category form, products are not saved ...

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; } } 
+4
source share
1 answer

As a bi-directional, you need to update the association on both sides.

Add this function to the Category object (you can call it addChild if you want):

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

And then update both associations at the same time:

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

Tip. Do not use $ children / $ parent to describe Entities. Call it that this is $ category / $ product, you will encounter problems when you want to add to another "parent" relationship.

+8
source

Source: https://habr.com/ru/post/1412772/


All Articles