sql - 使用带条件的内连接的 Doctrine 查询构建器

标签 sql symfony doctrine-orm

我想使用 Doctrine 的查询构建器构建以下 SQL:

select c.*
from customer c
join phone p
on p.customer_id = c.id
and p.phone = :phone
where c.username = :username

首先我尝试

$qb->select('c')
    ->innerJoin('c.phones', 'p', Join::ON, $qb->expr()->andx(
        $qb->expr()->eq('p.customerId', 'c.id'),
        $qb->expr()->eq('p.phone', ':phone')
    ))
    ->where('c.username = :username');

但是我收到以下错误

Error: expected end of string, got 'ON'

然后我尝试了

$qb->select('c')
    ->innerJoin('c.phones', 'p')
    ->where('c.username = :username')
    ->andWhere('p.phone = :phone');

这似乎有效。但是,有人知道第一次尝试出了什么问题吗?我想让第一个起作用,因为它更接近于 SQL 的结构。

注意:我知道我们也可以使用 Doctrine 编写 native mysql 或 dql,但我更喜欢查询构建器。

编辑:下面是整个代码

namespace Cyan\CustomerBundle\Repository;

use Cyan\CustomerBundle\Entity\Customer;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query\Expr\Join;

class CustomerRepository extends EntityRepository
{
    public function findCustomerByPhone($username, $phone)
    {
        $qb = $this->createQueryBuilder('c');

        $qb->select('c')
            ->innerJoin('c.phones', 'p', Join::ON, $qb->expr()->andx(
                $qb->expr()->eq('p.customerId', 'c.id'),
                $qb->expr()->eq('p.phone', ':phone')
            ))
            ->where('c.username = :username');

//        $qb->select('c')
//            ->innerJoin('c.phones', 'p')
//            ->where('c.username = :username')
//            ->andWhere('p.phone = :phone');

        $qb->setParameters(array(
            'username' => $username,
            'phone' => $phone->getPhone(),
        ));

        $query = $qb->getQuery();
        return $query->getResult();
    }
}

最佳答案

我要回答我自己的问题。

  1. innerJoin 应使用关键字“WITH”而不是“ON”(Doctrine 的文档 [13.2.6. Helper 方法] 不准确;[13.2.5. Expr 类] 正确)
  2. 无需在连接条件中链接外键,因为它们已在实体映射中指定。

因此,以下内容对我有用

$qb->select('c')
    ->innerJoin('c.phones', 'p', 'WITH', 'p.phone = :phone')
    ->where('c.username = :username')
    ->setParameter('phone', $phone)
    ->setParameter('username', $username);

$qb->select('c')
    ->innerJoin('c.phones', 'p', Join::WITH, $qb->expr()->eq('p.phone', ':phone'))
    ->where('c.username = :username')
    ->setParameter('phone', $phone)
    ->setParameter('username', $username);;

关于sql - 使用带条件的内连接的 Doctrine 查询构建器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15377079/

相关文章:

MySQL 快速检查 hash 是否存在

php - Symfony2 - 多种形式的主题

PHP Symfony 语义错误

php - 无法使用 symfony 和 doctrine 及其关联对象或表保存到 postgresql 中?

symfony - 有没有办法告诉 Doctrine 不要碰特定的 table ?

sql - 在 hive 表中导入系统名称、系统当前日期、时间

sql - 关于 SQL Server 中 INSERT 语句性能的建议

sql - 查询以查找在 sqlite 中存储为邻接列表的树中的下一个项目

php - Symfony2 删除 FormType 中的空字段

php - 如何在 Symfony 2 中返回实体的本地化属性