如何使用Doctrine2构建查询继承的内容? [英] How do I build something like query inheritance with Doctrine2?
问题描述
节点有:
- 一个'已发布的'字段,它是一个布尔
- 一个'locale'字段,它是一个字符串,并说'这个只能在本地区显示。 (该语言环境通过请求传入)
默认情况下,我只想显示来自当前语言环境的已发布节点
显然,我可以在存储库中创建许多查询,如下所示:
code $ $ this-> createQueryBuilder('Event')
- >其中('Node.published = 1')
- >其中('Node.locale =:locale ')
但这看起来不是很干燥。
那么如何构建其他查询可以继承的默认查询?这应该包括基于关系的默认原则查询。
继承可能是过度的。
为什么不创建一个给你预先配置的queryBuilder的一个工厂方法?
class NodeRepository extends Doctrine\ ORM\EntityRepository {
public function getLocalizedNodeQueryBuilder($ type,$ locale){
return $ this-> getQueryBuilder($ type)
- > where('Node .published = 1')
- > where('Node.locale =:locale')
- > setParameter('locale',$ locale);
}
}
你可以做同样的事情,只需重写getQueryBuilder如果您确定您一直希望以这种方式配置您的querybuilder。
I'm building a small website with Symfony2 and Doctrine2. There are blog posts, events and press releases. Each of these is so similar that I decided to use single table inheritance (STI) with a parent table called 'Node'.
Nodes have:
- a 'published' field, which is boolean
- a 'locale' field, which is a string and says 'this is only to be shown in this locale'. (The locale is passed in via the request).
By default, I only want to display published nodes that are from the current locale.
Obviously, I could create lots of queries in the repository that look something like:
$this->createQueryBuilder('Event')
->where('Node.published = 1')
->where('Node.locale = :locale')
but this doesn't seem very DRY.
So how do I build a default query which other queries can 'inherit' from? This should include default Doctrine queries based on relations.
Inheritance is probably overkill.
Why not just create a little factory method that gives you a preconfigured queryBuilder?
class NodeRepository extends Doctrine\ORM\EntityRepository {
public function getLocalizedNodeQueryBuilder($type,$locale){
return $this->getQueryBuilder($type)
->where('Node.published = 1')
->where('Node.locale = :locale')
->setParameter('locale',$locale);
}
}
You could do the same thing, and simply override getQueryBuilder if you're sure you always want your querybuilder configured that way.
这篇关于如何使用Doctrine2构建查询继承的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!