Symfony2教义FindOneOrCreate [英] Symfony2 doctrine FindOneOrCreate
问题描述
与推进我们有 findOneOrCreate()
示例。
$bookTag = BookTagQuery::create()
->filterByBook($book)
->findOneOrCreate();
在控制器中的任何地方,我们可以做这样的事情。
In doctrine anywhere in the controller We can do something like that.
...................
$filename='something';
$document_exists = $em->getRepository('DemoBundle:Document')
->findOneBy(array('filename' => $filename));
if (null === $document_exists) {
$document = new Document();
$document->setFilename($filename);
$em->persist($document);
$em->flush();
}
在Doctrine还有另一种方法来实现吗?
Is there another way to achieve this in Doctrine?
可以在Entity Repository中调用Entity Manager吗?
任何建议?
Is it OK to call the Entity Manager inside the Entity Repository? Any suggestions?
推荐答案
最简单的方法是扩展基础仓库:
Easiest way is to extend the base repository:
// src/Acme/YourBundle/Entity/YourRepository.php
namespace Acme\YourBundle\Entity;
use Doctrine\ORM\EntityRepository;
class YourRepository extends EntityRepository
{
public function findOneOrCreate(array $criteria)
{
$entity = $this->findOneBy($criteria);
if (null === $entity)
{
$entity = new $this->getClassName();
$entity->setTheDataSomehow($criteria);
$this->_em->persist($entity);
$this->_em->flush();
}
return $entity
}
}
然后告诉您的实体使用这个存储库或进一步扩展特定实体:
Then tell your entity to use this repository or extend in even further for specific entities:
// src/Acme/StoreBundle/Entity/Product.php
namespace Acme\StoreBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass="Acme\YourBundle\Entity\YourRepository")
*/
class Product
{
//...
}
并使用它在控制器中:
$em = $this->getDoctrine()->getManager();
$product = $em->getRepository('AcmeStoreBundle:Product')
->findOrCreate(array('foo' => 'Bar'));
资料来源: http://symfony.com/doc/current/book/doctrine.html#custom-repository-classes
只需要知道库中的 flush
,因为它将以这种方式刷新EntityManager中所有未保存的更改。
Just be aware of that flush
inside the repository as it would flush all unsaved changes in the EntityManager this way.
这篇关于Symfony2教义FindOneOrCreate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!