在多对多关系中应用doctrine sql过滤器

时间:2012-09-04 11:02:51

标签: php doctrine-orm

我的项目中有很多关系(user_role,grade,user_role_grades)。但我还要求不要从我的数据库中删除任何数据。所以,我在表中添加了一个状态列,连接2个表以创建多对多的关系。现在我想要

 $userRole->getGrades() 

只获取那些记录,在unite table(user_role_grades)中没有状态“0”。对于那些,我试图使用doctrine sql过滤器。

namespace Bis\MpBundle\Filter;
use \Doctrine\ORM\Mapping\ClassMetaData;

class UserRoleGradeFilter extends \Doctrine\ORM\Query\Filter\SQLFilter
{
    public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias)
    {
        if("Bis\DefaultBundle\Entity\UserRoleGrade" == $targetEntity->name){

            return $targetTableAlias . '.status != 0';
        }

        return '';
    }
}

因此,它被称为Bis \ DefaultBundle \ Entity \ UserRole,但不适用于Bis \ DefaultBundle \ Entity \ UserRoleGrade实体。有什么想法吗?

或者你可能有其他一些想法,我该怎么做?

2 个答案:

答案 0 :(得分:1)

我不认为这是可能的,因为它直接附加SQL。 即使你尝试像SQL注入一样:

return $targetTableAlias . '.status != 0)) LEFT join the_other_table ON  '
. $targetTableAlias . '.grades HAVING the_other_table.status = 0 ((';

它可能会在(())

之类的声明中崩溃

答案 1 :(得分:0)

您可以致电$targetEntity->getAssociationMappings()['yourFieldName'] 并且如果存在joinTable键,则表明您具有manyToMany关系。 yourFieldNameManyToMany关系的字段。

您可以从Doctrine\ORM\Query\SqlWalker::getSQLTableAlias()获取正确的表别名。 我得到SqlWalkerdebug_backtrace的帮助,这不是一个优雅的解决方案,但更好的是我还没有找到。

/**
 * Get SqlWalker with debug_backtrace
 *
 * @return null|SqlWalker
 */
protected function getSqlWalker()
{
    $caller = debug_backtrace();
    $caller = $caller[2];

    if (isset($caller['object'])) {
        return $caller['object'];
    }

    return null;
}

我的addFilterConstraint方法的完整实现

    public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias)
{
    if (empty($this->reader)) {
        return '';
    }

    // The Doctrine filter is called for any query on any entity
    // Check if the current entity is "pool aware" (marked with an annotation)
    $poolAware = $this->reader->getClassAnnotation(
        $targetEntity->getReflectionClass(),
        PoolAware::class
    );
    if (!$poolAware) {
        return '';
    }

    if (!$poolId = $this->getParameter('poolId')) {
        return '';
    }

    $fieldName = $poolAware->getFieldName();
    if (empty($fieldName)) {
        return '';
    }

    if (!$sqlWalker = $this->getSqlWalker()) {
        return '';
    }

    if (!isset($targetEntity->getAssociationMappings()[$fieldName])) {
        return '';
    }

    $mapping = $targetEntity->getAssociationMappings()[$fieldName];

    if (isset($mapping['joinColumns'])) {
        // oneToMany relation detected
        $table = $targetEntity->getTableName();
        $columnName = $mapping['joinColumns'][0]['name'];
        $dqlAlias = constant($targetEntity->getName() . '::MNEMO');
    } elseif (isset($mapping['joinTable'])) {
        // manyToMany relation detected
        $dqlAlias = constant($mapping['targetEntity'] . '::MNEMO');
        $component = $sqlWalker->getQueryComponent($dqlAlias);

        // Only main entity in query is interesting for us,
        // otherwise do not apply any filter
        if ($component['parent']) {
            return '';
        }
        $table = $mapping['joinTable']['name'];
        $columnName = $mapping['joinTable']['inverseJoinColumns'][0]['name'];
    } else {
        return '';
    }

    $tableAlias = ($sqlWalker instanceof BasicEntityPersister)
        ? $targetTableAlias // $repository->findBy() has been called
        : $sqlWalker->getSQLTableAlias($table, $dqlAlias);

    $query = sprintf('%s.%s = %s', $tableAlias, $columnName, $this->getConnection()->quote(poolId));

    return $query;
}

我们所有的学说模型都具有MNEMO常数,这是模型的简单名称。 Abc\Module\Model\Product具有MNEMO product。此MNEMO相当于存储库类中的_alias。这就是为什么我们将此值应用于$dqlAlias

您可以阅读here

的完整代码说明