假设以下AbstractPage
模型:
/*
* @ORM\Entity
* @ORM\Table(name="page")
* @ORM\InheritanceType("SINGLE_TABLE")
* @ORM\DiscriminatorColumn(name="type", type="string")
* @ORM\DiscriminatorMap
* ({
* "page" = "Page",
* "link" = "Link"
* })
*/
以下DQL查询:
SELECT p FROM \Page\Model\AbstractPage
生成的SQL将是:
SELECT ... FROM page p0_ WHERE p0_.type IN ('page', 'link')
现在问题:如何从此查询中删除WHERE
子句。在更复杂的查询中,WHERE
子句的这一部分使得无法使用已定义的某些索引。这可以通过向索引添加type
来解决,但这会使我的索引变大,我觉得这不是必需的。
AbstractPage
是继承树中的根。因此,我们对表中的所有记录感兴趣。省略WHERE
部分恰恰就是这样。
所以问题是:如何让Doctrine删除不需要的WHERE
部分。
谢谢!
答案 0 :(得分:4)
这是我能想到的解决方案。我们的想法是扩展一些学说类以添加所需的功能。 保持模型不变。
创建扩展SqlWalker的新类(当然更新名称空间)
<?php
namespace Sad;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Query\SqlWalker;
class CustomSqlWalker extends SqlWalker
{
const IGNORE_DISCRIMINATION = 'ignoreDiscrimination';
/**
* {@inheritdoc}
*/
public function walkWhereClause($whereClause)
{
// Get list of aliases in which discrimination should be ignored
$ignoreDescription = $this->getQuery()->getHint(self::IGNORE_DISCRIMINATION);
if ($ignoreDescription !== false) {
// For each aliases...
foreach ($this->getQueryComponents() as $k => $component) {
// ...check if alias is in ignore list
if (in_array($k, $ignoreDescription)) {
/** @var $metaObj ClassMetadata */
$metaObj = $component['metadata'];
// Update inheritance type to disable discrimination where
if ($metaObj->isInheritanceTypeSingleTable()) {
$metaObj->setInheritanceType(ClassMetadata::INHERITANCE_TYPE_NONE);
}
}
}
}
return parent::walkWhereClause($whereClause);
}
}
然后进行查询,请执行以下操作:
echo $entityManager->createQuery("SELECT p FROM \Sad\Schema\AbstractPage as p")->getSQL();
// Output: ELECT p0_.id AS id_0, p0_.name AS name_1, p0_.type AS type_2 FROM page p0_ WHERE p0_.type IN ('page', 'link')
$query = $entityManager->createQuery("SELECT p FROM \Sad\Schema\AbstractPage as p");
// Make sure query uses custom walker
$query->setHint(\Doctrine\ORM\Query::HINT_CUSTOM_OUTPUT_WALKER, 'Sad\CustomSqlWalker');
// Specify which aliases should ignore discrimination
$query->setHint(\Sad\CustomSqlWalker::IGNORE_DISCRIMINATION, array('p'));
echo $query->getSQL();
// Output: ELECT p0_.id AS id_0, p0_.name AS name_1, p0_.type AS type_2 FROM page p0_