使用doctrine 2查询构建器加入3表

时间:2014-12-19 07:25:49

标签: php mysql doctrine-orm doctrine codeigniter-2

嘿伙计们我有三张桌子

1) expert_class
2) expert_location
3) expert

我想从mysql中的所有三个表中获取数据,即

select * from expert_class class 
join expert_location loc 
on loc.expert_id = class.expert_id 
join expert e 
on class.expert_id = e.id 
where e.is_delete=0

使用此查询我得到了我想要的所有数据,但问题是我必须使用doctrine查询bulider编写此查询我试过这样

$classes = $this->qb
                    ->add('select', 'exp_cls,exp_loc.id as location_id')
                    ->from('Entity\expert_class','exp_cls')
                    ->join('Entity\expert_location', 'exp_loc')
                    ->join('Entity\expert', 'exp')
                    ->where('exp_cls.expert_id = exp.id')
                    ->AndWhere('exp_cls.expert_id = exp_loc.expert_id')
                    ->AndWhere('exp.is_delete = 0')
                    ->getQuery()
                    ->getArrayResult(); 

当我尝试运行此查询时,我收到了致命错误

Fatal error: Uncaught exception 'Doctrine\ORM\Query\QueryException' with message 'SELECT exp_cls,exp_loc.id as location_id FROM Entity\expert_class exp_cls INNER JOIN Entity\expert_location exp_loc INNER JOIN Entity\expert exp WHERE exp_cls.expert_id = exp.id AND exp_cls.expert_id = exp_loc.expert_id AND exp.is_delete = 0' in C:\xampp\htdocs\projectname\application\libraries\Doctrine\ORM\Query\QueryException.php:39 Stack trace: #0 C:\xampp\htdocs\projectname\application\libraries\Doctrine\ORM\Query\Parser.php(396): Doctrine\ORM\Query\QueryException::dqlError('SELECT exp_cls,...') #1 C:\xampp\htdocs\projectname\application\libraries\Doctrine\ORM\Query\Parser.php(2363): Doctrine\ORM\Query\Parser->syntaxError('Literal') #2 C:\xampp\htdocs\projectname\application\libraries\Doctrine\ORM\Query\Parser.php(2550): Doctrine\ORM\Query\Parser->Literal() #3 C:\xampp\htdocs\projectname\application\libraries\Doctrine\ORM\Query\Parser.php(2485): Doctrine\ORM\Query\Parser-> in C:\xampp\htdocs\projectname\application\libraries\Doctrine\ORM\Query\QueryException.php on line 44

我也查了这个链接Doctrine query builder using inner join with conditions,但没有帮助

1 个答案:

答案 0 :(得分:0)

您是否在实体中定义了关系? E.g:

/**
 * @var ArrayCollection
 *
 * @ORM\OneToMany(targetEntity="expert_location", mappedBy="locations")
 */
private $location;

如果你这样做,那么你必须在你的联接中使用这些连接,例如:

->join('exp_cls.locations', 'exp_loc')  // This joins the expert_location entity

你没有,那么你应该添加ON条件:

use Doctrine\ORM\Query\Expr\Join;

...

->join('Entity\expert_location', 'exp_loc', Join::ON, $qb->expr()->eq('exp_loc.expert_id', 'exp_cls.expert_id '))
相关问题