Symfony2/Doctrine2 innerJoin 使用 QueryBuilder

Symfony2/Doctrine2 innerJoin using QueryBuilder

我正在尝试使用 Doctrine2/QueryBuilder.

构建 innerJoin 查询
$repo =  $this->getDoctrine()
        ->getRepository('MyBundle:Models');
$query = $repo->createQueryBuilder('m')
        ->where('m.id = :id')
        ->setParameter('id', $id);

学说说:

A join always belongs to one part of the from clause. This is why you have to specify the alias of the FROM part the join belongs to as the first argument.

As a second and third argument you can then specify the name and alias of the join-table and the fourth argument contains the ON clause.

例如

$queryBuilder
->innerJoin('u', 'phonenumbers', 'p', 'u.id = p.user_id');

我无法理解的是 'phonenumbers' table 指的是 Entity NameDB Table Name.

我真正想要的是,有什么方法可以显式引用像

这样的实体

innerJoin('u', 'MyBundle:phonenumbers', 'p', 'u.id = p.user_id')?

就这样加入的时候有点乱。有人可以给我解释一下吗?

求助!!

事实上,您已经在 innerJoin 函数的第二个参数中明确引用了实体 phonenumbers。

您阅读了文档,我会根据您的要求逐点重温:

  • 参数 1:FROM 部分的别名,这里是您的 m(您的模型的别名)
  • 参数 2:您想要加入模型的实体的全名
  • 参数 3:访问​​它的别名(就像模型的 'm')
  • 参数 4:连接条件。 (就像 sql 请求的 ON 部分)

但是对于 symfony,如果你的两个实体之间有这样的关系:

//AppBundle/Entity/Models

    class Models {
        /**
         * ...
        **/
        private $id;

        /**
         * ...
         * @ORM\ManyToOne(targetEntity="\AppBundle\Entity\Phone", inversedBy="models")
         **/
        private $phonenumbers;

        ...
    }

你想加入你就可以做到:

$repo =  $this->getDoctrine()
        ->getRepository('MyBundle:Models');
$query = $repo->createQueryBuilder('m')
        ->innerJoin('m.phonenumbers', 'p')
        ->where('m.id = :id')
        ->setParameter('id', $id);

解释一下:您只需将要加入的实体 属性 作为第一个参数传递(这里是模型的 phone 编号)并将其定义为别名(p for phone访问它的号码 select)

您正在使用 tables 的 DQL 级别工作,这意味着您实际上加入了一个 table,因此您只需要 table 名称,而不是实体名称。 table "phonenumbers 甚至可能没有实体开头,这就是为什么 Doctrine 要求 table 名称而不是实体名称。

编辑

实际上可以使用实体名称以及以下内容(取自我自己的代码,它很有魅力):

$builder = $this->createQueryBuilder('m');
$builder->innerJoin(
    'YourBundle:Category',
    'c',
    Join::WITH,
    $builder->expr()->eq('m.id', 'c.mdl_id')
);

要使用 Join 中的常量,您首先应该:

use Doctrine\ORM\Query\Expr\Join;

但这也应该有效(取自文档,这意味着应该像魅力一样工作):

$queryBuilder
    ->select('id', 'name')
    ->from('users', 'u')
    ->innerJoin('u', 'phonenumbers', 'p', 'u.id = p.user_id');

这是采取的形式:http://doctrine-orm.readthedocs.org/projects/doctrine-dbal/en/latest/reference/query-builder.html#join-clauses