gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 07:43:52 25 4
gpt4 key购买 nike

我想使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com