[英]Doctrine 2 - Class Table Inheritance, selecting by type
I have two entities - News and Page. 我有两个实体 - 新闻和页面。 Definition looks like this:
定义如下:
/** * Description of Page * @Entity * @InheritanceType("JOINED") * @DiscriminatorColumn(name="type", type="string") * @DiscriminatorMap({ * "news" = "News" , * "page" = "Page"}) * * @table( * name="pages" * ) */ class Page extends BaseEntity {...} class News extends Page {...}
I know, how to select only "news" entities - simple SELECT ... FROM News n
. 我知道,如何只选择“新闻”实体 - 简单的
SELECT ... FROM News n
。
But is there some way how to select only "page" entities, which are mapped directly to Page class? 但有没有办法如何只选择“页面”实体,它们直接映射到Page类? Or do I have to create some extra entity extending Page for this?
或者我是否必须为此创建一些额外的实体扩展页面?
The solution is to use x INSTANCE OF Entity
in WHERE clause. 解决方案是在WHERE子句中使用
x INSTANCE OF Entity
。
http://groups.google.com/group/doctrine-user/browse_thread/thread/b1dc52ed447204e2 http://groups.google.com/group/doctrine-user/browse_thread/thread/b1dc52ed447204e2
The solution, that I use is that I create a Switcher on the root entity Repository
class, like so: 我使用的解决方案是在根实体
Repository
类上创建一个Switcher,如下所示:
class PageRepository extends EntityRepository
{
protected $_switchEntityNameSave = null;
/**
* @param type $fqcn
*/
protected function _swapEntityDiscriminator($fqcn = null){
if(isset($fqcn)){
$this->_switchEntityNameSave = $this->_entityName;
$this->_entityName = $fqcn;
} else {
$this->_entityName = $this->_switchEntityNameSave;
unset($this->_switchEntityNameSave);
}
}
// ... AND TO USE...
public function findSomeStuff()
{
$this->_swapEntityDiscriminator(News::getFqcn());
// The query, the result in a variable, $q for example
$this->_swapEntityDiscriminator();
return $q->getQuery();
}
}
Then, in the parent classe, I do the Getter getFqcn()
, like so: 然后,在父classe中,我执行Getter
getFqcn()
,如下所示:
abstract class BaseEntity {
/**
* Get fqcn
*
* Fully Qualified Class Name
*
* @return string
*/
public static function getFqcn()
{
return get_called_class();
}
// ...
}
That use the Late static binding feature and give me the full class name on the concrete object (either News
or Page
). 这使用Late静态绑定功能,并在具体对象(
News
或Page
)上提供完整的类名称。
I do put abstract, to be sure to not instantiate it. 我确实放了抽象,以确保不实例化它。
What I also add in the concrete classes, a few constants: 我还在具体类中添加了一些常量:
class News extends Page {
const HUMAN_READABLE = "News";
const DISCRIMINATOR = "news"; // SAME as your @DiscriminatorMap() Annotation.
}
That way, my Repository
I can create specialized finders only on one of the types. 这样,我的
Repository
我只能在其中一种类型上创建专门的查找程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.