有了 propel,我们就有了 findOneOrCreate()
示例。
$bookTag = BookTagQuery::create()
->filterByBook($book)
->findOneOrCreate();
在 Controller 的任何地方我们都可以做类似的事情。
...................
$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 中是否有其他方法可以实现这一目标?
可以在实体存储库中调用实体管理器吗? 有什么建议吗?
最佳答案
最简单的方法是扩展基础存储库:
// 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
}
}
然后告诉您的实体使用此存储库或进一步扩展特定实体:
// 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
{
//...
}
并在您的 Controller 中使用它:
$em = $this->getDoctrine()->getManager();
$product = $em->getRepository('AcmeStoreBundle:Product')
->findOrCreate(array('foo' => 'Bar'));
来源:http://symfony.com/doc/current/book/doctrine.html#custom-repository-classes
请注意存储库内的刷新
,因为它会以这种方式刷新 EntityManager 中所有未保存的更改。
关于Symfony2主义FindOneOrCreate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17935647/