Doctrine query builder using inner join with conditions

前端 未结 2 1437
傲寒
傲寒 2020-12-03 04:20

I\'d like to construct the following SQL using Doctrine\'s query builder:

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


        
2条回答
  •  温柔的废话
    2020-12-03 05:17

    You can explicitly have a join like this:

    $qb->innerJoin('c.phones', 'p', Join::ON, 'c.id = p.customerId');
    

    But you need to use the namespace of the class Join from doctrine:

    use Doctrine\ORM\Query\Expr\Join;
    

    Or if you prefere like that:

    $qb->innerJoin('c.phones', 'p', Doctrine\ORM\Query\Expr\Join::ON, 'c.id = p.customerId');
    

    Otherwise, Join class won't be detected and your script will crash...

    Here the constructor of the innerJoin method:

    public function innerJoin($join, $alias, $conditionType = null, $condition = null);
    

    You can find other possibilities (not just join "ON", but also "WITH", etc...) here: http://docs.doctrine-project.org/en/2.0.x/reference/query-builder.html#the-expr-class

    EDIT

    Think it should be:

    $qb->select('c')
        ->innerJoin('c.phones', 'p', Join::ON, 'c.id = p.customerId')
        ->where('c.username = :username')
        ->andWhere('p.phone = :phone');
    
        $qb->setParameters(array(
            'username' => $username,
            'phone' => $phone->getPhone(),
        ));
    

    Otherwise I think you are performing a mix of ON and WITH, perhaps the problem.

提交回复
热议问题