我在最新版本中使用Symfony 2.7和Doctrine。 我尝试了他们的多对一双向示例:
现在我可以使用我的控制器添加产品,但它不会更新我的功能。
以下是产品实体的代码:
<?php
namespace AppBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/** @ORM\Entity
*
* @ORM\Table(name="product")
*
*/
class Product
{
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\OneToMany(targetEntity="Feature", mappedBy="product")
**/
private $features;
public function __construct() {
$this->features = new ArrayCollection();
}
public function getId()
{
return $this->id;
}
public function addFeature(Feature $feature)
{
return $this->features[] = $feature;
}
public function getFeatures()
{
return $this->features;
}
}
以及要素实体的代码:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/** @ORM\Entity
*
* @ORM\Table(name="feature")
*
*/
class Feature
{
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\ManyToOne(targetEntity="Product", inversedBy="features")
* @ORM\JoinColumn(name="product_id", referencedColumnName="id")
**/
private $product;
public function getId()
{
return $this->id;
}
public function getProduct()
{
return $this->product;
}
public function setProduct($product)
{
$this->product = $product;
}
}
在我的控制器中,我只需创建一个新产品和一项新功能,并将该功能添加到我的产品实体中:
<?php
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use AppBundle\Entity\Product;
use AppBundle\Entity\Feature;
use Symfony\Component\HttpFoundation\Response;
class DefaultController extends Controller
{
/**
* @Route("/")
*/
public function indexAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$feature = new Feature();
$product = new Product();
$product->addFeature($feature);
$em->persist($feature);
$em->persist($product);
$em->flush();
return new Response('Created product id '.$product->getId());
}
}
我只获得了新产品和新功能。该功能无法获得与产品的关系(数据库中的product_id字段包含“NULL”)。
答案 0 :(得分:1)
尝试将addFeature
类的Product
方法更改为
public function addFeature(Feature $feature)
{
return $this->features->add($feature->setProduct($this));
}
并将setProduct
类的Feature
方法更改为
public function setProduct($product)
{
$this->product = $product;
// For chaining
return $this;
}
如果这些更改无法解决您的问题,请尝试将$features
属性注释更改为
/**
* @ORM\OneToMany(targetEntity="Feature", mappedBy="product", cascade={"persist", "remove"})
**/
private $features;
cascade
选项告诉Doctrine自动管理子实体。