作为我网站的一部分,我正在尝试使用Symfony2和Doctrine2创建标记(folksonomy)系统。
我正在按照下面的文档中的表格和查询示例来创建我的Doctrine实体:http://dablog.ulcc.ac.uk/wp-content/uploads/2007/12/tagging_folksonomy.pdf
当我尝试将MySQL查询(在文档中给出)转换为Doctrine Query Builder查询时,我得到了innerJoins的错误。示例如下:
来自文档的MySQL查询:
SELECT tag_text
, COUNT(*) as num_tags
FROM Tag2Post t2p
INNER JOIN Tags t
ON t2p.tag_id = t.tag_id
GROUP BY tag_text;
我的Doctrine查询生成器查询:
$qb = $em->createQueryBuilder()
->select('t.tag_text, COUNT(*) as num_tags')
->from('CompanyWebsiteBundle:Tag2Post', 't2p')
->innerJoin('CompanyWebsiteBundle:Tags', 't', 'ON', 't2p.tag_id = t.id')
->groupBy('t.tag_text')
;
$tags = $qb->getQuery()->getResult();
错误讯息:
[2/2] QueryException: [Syntax Error] line 0, col 112: Error: Expected Doctrine\ORM\Query\Lexer::T_WITH, got 'ON'
[1/2] QueryException: SELECT t.tag_text, COUNT(*) as num_tags FROM CompanyWebsiteBundle:Tag2Post t2p INNER JOIN CompanyWebsiteBundle:Tag t ON t2p.tag_id = t.id GROUP BY t.tag_text
当我直接在数据库上运行MySQL查询时,它可以工作!
答案 0 :(得分:10)
这应该有效。在DQL中,ON
关键字由WITH
替换。
$qb = $em->createQueryBuilder()
->select('t.tag_text, COUNT(*) as num_tags')
->from('CompanyWebsiteBundle:Tag2Post', 't2p')
->innerJoin('CompanyWebsiteBundle:Tags', 't', 'WITH', 't2p.tag_id = t.id')
->groupBy('t.tag_text')
;
$tags = $qb->getQuery()->getResult();
此外,如果你有正确配置的实体,你应该可以省略, 'WITH', 't2p.tag_id = t.id'
部分,因为学说应该自动找到关系。
例如:
$qb = $em->createQueryBuilder()
->select('t.tag_text, COUNT(*) as num_tags')
->from('CompanyWebsiteBundle:Tag2Post', 't2p')
->innerJoin('t2p.tags', 't')
->groupBy('t.tag_text')
;
$tags = $qb->getQuery()->getResult();