php Doctrine 中的左连接 ON 条件和其他条件语法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19185587/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 18:59:05  来源:igfitidea点击:

Left join ON condition AND other condition syntax in Doctrine

phpmysqlsqlsymfonydoctrine-orm

提问by juuga

I'm using Doctrine's querybuilder in Symfony2 to create a query to fetch entities.

我在 Symfony2 中使用 Doctrine 的查询构建器来创建一个查询来获取实体。

My current code looks like this:

我当前的代码如下所示:

$repository = $this->getDoctrine()->getRepository('AaaBundle:Application');

    $queryBuilder = $repository->createQueryBuilder('a');
    $queryBuilder
        ->addSelect('u')
        ->addSelect('i')
        ->orderBy('a.created_date', 'DESC')
        ->leftJoin('a.created_by', 'u')
        ->leftJoin('a.installations', 'i')
        //->where('i.page = :page')
        //->setParameter('page', $found)
        ;

Now I can use this to get all the pages regardless of them having an installation or not. But I only want to join them it the $foundpage is available (so that if there is an installation for the app, but it's on another page, the installation wont be joined). If I unquote the where clause, it will show only apps that have an installation for the page. I want all apps with or without installations for the page.

现在我可以使用它来获取所有页面,无论它们是否安装。但是我只想在$found页面可用时加入他们(这样,如果应用程序安装了,但它在另一个页面上,则不会加入安装)。如果我取消引用 where 子句,它将仅显示已安装该页面的应用程序。我想要页面上安装或不安装的所有应用程序。

In SQL I can get this by adding ANDto the join

在 SQL 中,我可以通过添加AND到连接来获得它

LEFT JOIN installations i ON a.id = i.app AND i.page = :page

This way I get the installation info for an app that has an installation on the page, but I get null values on the columns for app's that have installations on other pages or not at all.

通过这种方式,我获得了在页面上安装的应用程序的安装信息,但我在其他页面上安装或根本没有安装的应用程序列上获得了空值。

Is there a way to do this in Doctrine or am I better off just getting all the installations for each application and then checking against the found page with php?

有没有办法在 Doctrine 中做到这一点,或者我最好只获取每个应用程序的所有安装,然后用 php 检查找到的页面?

回答by zapcost

You can try this :

你可以试试这个:

use Doctrine\ORM\Query\Expr;

->leftJoin('a.installations', 'i', Expr\Join::WITH, 'i.page = :page')
->setParameter('page', $page)

See function leftJoin in doc: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/query-builder.html#high-level-api-methods

请参阅文档中的 leftJoin 函数:http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/query-builder.html#high-level-api-methods