Doctrine中的自定义QueryBuilder [英] Custom QueryBuilder in Doctrine
本文介绍了Doctrine中的自定义QueryBuilder的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我遇到这个问题,我想创建智能条件。假设有一个作者为1的模型:n本书。
I have this problem, I would like to create "smart" criteria. Suppose there's a model of 1 Author : n Books.
因此,而不是:
$qb = $em->getRepository('Books')->createQueryBuilder('b')
->join('b.author', 'a')
->where('a.dod is null')
->where('a.name = :name')
->setParameter('name', 'Mozart');
;
...我想做类似的事情:
...i'd like to do something like:
$qb = $em->getRepository('Books')->createQueryBuilder('b')
->whereAuthorIsAlive()
->whereAuthorName('Mozart');
我知道创建自定义EntityManager的可能性,但事实并非如此。
I am aware of the possibility to creating custom EntityManager but this is not quite it. Custom QueryBuider would be more suitable.
推荐答案
您可以使用自定义方法扩展QueryBuilder,但是通过覆盖QueryBuilder会产生一些开销。存储库的 createQueryBuilder
方法:
You could extend the QueryBuilder with your custom methods, but have a little overhead by overwriting the createQueryBuilder
method of your repository:
- 扩展默认的QueryBuilder类:
class BookQueryBuilder extends \Doctrine\ORM\QueryBuilder
{
public function whereAuthorIsAlive(): self
{
return $this->join($this->getRootAlias() . '.author', '_a')
->andWhere('_a.alive = true');
}
}
- 在您的存储库中,覆盖
createQueryBuilder
方法:
- In your Repository, overwrite the
createQueryBuilder
method:
class BookRepository extends EntityRepository
{
public function createQueryBuilder($alias, $indexBy = null)
{
return (new BookQueryBuilder($this->_em))
->select($alias)
->from($this->_entityName, $alias, $indexBy);
}
}
- 使用新方法
$qb = $em->getRepository('Books')->createQueryBuilder('b')
->whereAuthorIsAlive();
这篇关于Doctrine中的自定义QueryBuilder的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文