cos*_*sta 6 php sql symfony doctrine-orm
我有一个多租户应用程序,我正在使用Doctrine Filters来过滤我的SQL客户端.
所以,当我想要一个我的客户端项目列表时,我只需要做一个"getAll",过滤器会自动在WHERE子句上附加SQL,如下所示:
SELECT *
FROM projects p
WHERE p.client_id = 1 #(appended by the filter)
Run Code Online (Sandbox Code Playgroud)
我的问题是当我想要例如ProjectMembers时.过滤器将SQL添加到LEFT JOIN,而不是WHERE子句,使得过滤器无用,因为它将返回所有ProjectMembers,即使它们不是来自客户端1.
SELECT *
FROM projects p
LEFT JOIN project_members pm ON pm.project_id = p.id
AND p.client_id = 1 #(appended by the filter)
Run Code Online (Sandbox Code Playgroud)
这是我的addFilterConstrait
public function addFilterConstraint(ClassMetaData $targetEntity, $targetTableAlias)
{
$class = $targetEntity->getName();
if (array_key_exists($class, $this->disabled) && $this->disabled[$class] === true) {
return '';
} elseif (array_key_exists($targetEntity->rootEntityName, $this->disabled) && $this->disabled[$targetEntity->rootEntityName] === true) {
return '';
}
$config = $this->getFilterConfig($targetEntity->getReflectionClass());
if (!isset($config['clientFilter']) || !$config['clientFilter']) {
return '';
}
return $targetTableAlias. '.' . $config['columnName'] . ' = ' . $this->getParameter('client'); // getParameter applies quoting automatically
}
Run Code Online (Sandbox Code Playgroud)
任何想法如何解决这个问题,将过滤器添加到WHERE而不是LEFT JOIN?
您在 Symfony 中执行的 SQL 越多,您很快就会发现为实体创建存储库、每个实体使用一个存储库或与多个实体共享公共存储库会变得更加容易。然后在存储库中写入您的 DQL。注意:DQL 很像 SQL,但它也有其局限性。
https://symfony.com/doc/3.3/doctrine/repository.html
然后就可以引用该函数了。
$em = $this->getDoctrine()->getManager();
$data = $em->getRepository(EntityClassName::class)->repositoryFunctionName($paramifyouhaveany);
Run Code Online (Sandbox Code Playgroud)