您可以致电$targetEntity->getAssociationMappings()['yourFieldName']
,如果joinTable
存在密钥,则表示您有manyToMany
关系。你yourFieldName
的领域与ManyToMany
关系。
您可以从中获得正确的表别名Doctrine\ORM\Query\SqlWalker::getSQLTableAlias()
。我得到SqlWalker
了debug_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;
}
我们所有的 Doctrine 模型都有 MNEMO 常量,它是模型的简单名称。Abc\Module\Model\Product
有 MNEMO product
。这个 MNEMO 相当于_alias
Repository 类。这就是为什么我们将此值应用于$dqlAlias
您可以在此处阅读完整的代码说明