我想使用 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();
}
}
最佳答案
我要回答我自己的问题。
- innerJoin 应使用关键字“WITH”而不是“ON”(Doctrine 的文档 [13.2.6. Helper 方法] 不准确;[13.2.5. Expr 类] 正确)
- 无需在连接条件中链接外键,因为它们已在实体映射中指定。
因此,以下内容对我有用
$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/