首页 文章

Doctrine2:多次调用flush

提问于
浏览
0

我对Symfony 2.3中的Doctrine和Entities有疑问 .

根据"Documentation Book"章节"Databases and Doctrine > Saving Related Entities"(请查看此处的示例:http://symfony.com/doc/current/book/doctrine.html),该示例同时在产品和类别表中创建新行,并将product.category_id值与新类别项的"id"相关联 .

问题是Action Controller在调用时会创建一个新产品和一个新类别!

为了创建一个新产品并将其category_id与现有的类别ID相关联(我通过url进行测试传递参数,如下所示:/ web / store / create / newproduct / Kayak / 12

这是routing.yml路由

acme_store_create_product_by_category:
path:     /create/newproduct/{name}/{categoryId}
defaults: { _controller: AcmeStoreBundle:Default:createProduct }

我做了类似这样的事情似乎工作得很好:

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()方法是一个好习惯吗?在这种情况下,我想创建一个新产品,从“列表框”中选择相关类别 .

先感谢您!

1 回答

  • 2

    我认为这主要取决于您的应用领域 . 如果你运行 flush 两次意味着你're running two transactions. In the first one you'重新持久产品,在第二个类别 . 因此,如果第一个事务失败(让's say you have a unique key on the product name and you'尝试持久保存具有相同名称的产品,以便获得重复的密钥异常),那么问问自己是否认为我们可以在这里轻松回答这个问题,因为我认为这取决于您的应用程序逻辑,该 endpoints 应该做什么,如果你最终拥有一个产品而不是一个类别,反之亦然,会发生什么 .

    您还应该考虑,如果您在第一次交易中遇到异常,您的代码就会知道如何管理事情 . 所以你'll have to reset it or you'会得到一个 EntityManager is closed 问题 .

    try {
        // first transaction
        $entityManager->persist($entityOne);
        $entityManager->flush();
    } catch (\Exception $e) {
        /* ... handle the exception */ 
        $entityManager->resetManager();
    }
    
    // now we can safely run a second transaction here
    

    我希望这回答了你的问题 :-)

相关问题