php 如何在 Doctrine 中进行左连接?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15087933/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to do left join in Doctrine?
提问by noobie-php
This is my function where I'm trying to show the User history. For this I need to display the user's current credits along with his credit history.
这是我尝试显示用户历史记录的功能。为此,我需要显示用户的当前信用以及他的信用历史。
This is what I am trying to do:
这就是我想要做的:
public function getHistory($users) {
$qb = $this->entityManager->createQueryBuilder();
$qb->select(array('a','u'))
->from('Credit\Entity\UserCreditHistory', 'a')
->leftJoin('User\Entity\User', 'u', \Doctrine\ORM\Query\Expr\Join::WITH, 'a.user = u.id')
->where("a.user = $users ")
->orderBy('a.created_at', 'DESC');
$query = $qb->getQuery();
$results = $query->getResult();
return $results;
}
However, I get this error :
但是,我收到此错误:
[Syntax Error] line 0, col 98: Error: Expected Doctrine\ORM\Query\Lexer::T_WITH, got 'ON'
[语法错误] line 0, col 98: Error: Expected Doctrine\ORM\Query\Lexer::T_WITH, got 'ON'
Edit: I replaced 'ON' with 'WITH' in the join clause and now what I see is only 1 value from the joined column.
编辑:我在连接子句中用 'WITH' 替换了 'ON',现在我看到的只有来自连接列的 1 个值。
回答by Ocramius
If you have an association on a property pointing to the user (let's say Credit\Entity\UserCreditHistory#user, picked from your example), then the syntax is quite simple:
如果您在指向用户的属性上有关联(比方说Credit\Entity\UserCreditHistory#user,从您的示例中选择),则语法非常简单:
public function getHistory($users) {
$qb = $this->entityManager->createQueryBuilder();
$qb
->select('a', 'u')
->from('Credit\Entity\UserCreditHistory', 'a')
->leftJoin('a.user', 'u')
->where('u = :user')
->setParameter('user', $users)
->orderBy('a.created_at', 'DESC');
return $qb->getQuery()->getResult();
}
Since you are applying a condition on the joined result here, using a LEFT JOINor simply JOINis the same.
由于您在此处对连接结果应用条件,因此使用LEFT JOINorJOIN是相同的。
If no association is available, then the query looks like following
如果没有可用关联,则查询如下所示
public function getHistory($users) {
$qb = $this->entityManager->createQueryBuilder();
$qb
->select('a', 'u')
->from('Credit\Entity\UserCreditHistory', 'a')
->leftJoin(
'User\Entity\User',
'u',
\Doctrine\ORM\Query\Expr\Join::WITH,
'a.user = u.id'
)
->where('u = :user')
->setParameter('user', $users)
->orderBy('a.created_at', 'DESC');
return $qb->getQuery()->getResult();
}
This will produce a resultset that looks like following:
这将产生一个如下所示的结果集:
array(
array(
0 => UserCreditHistory instance,
1 => Userinstance,
),
array(
0 => UserCreditHistory instance,
1 => Userinstance,
),
// ...
)

