【发布时间】:2015-10-08 09:03:24
【问题描述】:
我对 Symfony 2.3 上的 Doctrine 和实体有疑问。
根据 v2.3 "Documentation Book" 章节 "Databases and Doctrine" > Saving Related Entities,该示例同时在 product 中创建一个新行和category 表格并将 product.category_id 值与新类别 项的id 关联。
问题在于控制器操作在任何时候都会创建一个新的Product和一个新的Category!
为了创建一个新的产品并将其category_id与现有的类别 id相关联,这是routing.yml强> 路线:
acme_store_create_product_by_category:
path: /create/newproduct/{name}/{categoryId}
defaults: { _controller: AcmeStoreBundle:Default:createProduct }
我做了一个通过 URL 传递参数的测试:
/web/store/create/newproduct/Kayak/12
我做了这样的事情,看起来工作正常:
public function createProductAction($name, $categoryId)
{
$em = $this->getDoctrine()->getManager();
if ( $em->getRepository("AcmeStoreBundle:Category")->findOneById($categoryId) ) {
$product = new Product();
$product->setName($name);
$product->setPrice(220);
$product->setDescription("This is just a test");
$em->persist($product);
$em->flush();
$newproduct = $em->getRepository("AcmeStoreBundle:Product")->find($product->getId());
/** Create new product and populate $newproduct with its data */
$repository = $em->getRepository("AcmeStoreBundle:Category")->find($categoryId);
$newproduct->setCategory($repository);
$em->persist($newproduct);
$em->flush();
/** Update the id_category field of the new product with parameter $categoryId */
//exit(\Doctrine\Common\Util\Debug::dump($product));
return new Response('Create product ' . $name . ' with category id ' . $categoryId);
} else {
return new Response('It doesn\'t exists any category with id ' . $categoryId);
}
}
在这种情况下我的疑问是:在同一个 action 中调用 flush() 方法两次是一个好习惯吗?在这种情况下,我想创建一个新的product,从“列表框”中选择相关的category。
提前谢谢你!
【问题讨论】:
标签: php symfony doctrine-orm doctrine