php 在 Symfony 2 中使用查询生成器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10856508/
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
Using Query Builder in Symfony 2
提问by Zoha Ali Khan
I am trying to use Query Builder in Symfony2 to get some records from a database. I run the normal query in SQL and it returns the correct results. The query is
我试图在 Symfony2 中使用查询生成器从数据库中获取一些记录。我在 SQL 中运行普通查询,它返回正确的结果。查询是
SELECT pg.name, pg.description
FROM pm_patentgroups pg
LEFT JOIN pm_portfolios pp ON pp.id = pg.portfolio_id
I want to use the exact query using Doctorine query builder in Symfony2. What I have tried so far is
我想在 Symfony2 中使用 Doctorine 查询构建器来使用确切的查询。到目前为止我尝试过的是
$repository = $this->getDoctrine()
->getRepository('MunichInnovationGroupBundle:PmPatentgroups');
$query = $repository->createQueryBuilder('pg')
->from('pm_patentgroups', 'pg')
->leftJoin('pg','pm_portfolios','pp','pp.id = pg.portfolio_id')
->getQuery();
$portfolio_groups = $query->getResult();
but its giving me the following error:
但它给了我以下错误:
Warning: Missing argument 1 for Doctrine\ORM\EntityRepository::createQueryBuilder()
警告:Doctrine\ORM\EntityRepository::createQueryBuilder() 缺少参数 1
I am new to Symfony2 and Doctorine. Can you please tell me what is going wrong here?
我是 Symfony2 和 Doctorine 的新手。你能告诉我这里出了什么问题吗?
Thanks
谢谢
回答by Fred Jiles
You are missing the alias when using createQueryBuilder. Since you have the repository you can drop the from portion and just use
使用 createQueryBuilder 时缺少别名。由于您拥有存储库,因此您可以删除 from 部分并使用
$query = $repository->createQueryBuilder('pg')
回答by Cerad
Something like:
就像是:
$qb = $this->getDoctrine()->createQueryBuilder();
$qb->addSelect('pm_patentgroups');
$qb->addSelect('pm_portfolios');
$qb->from('MunichInnovationGroupBundle:PmPatentgroups','pm_patentgroups');
$qb->leftJoin('pm_patentgroups.pm_portfolios','pm_portfolios');
This assumes you have your two entities properly related.
这假设您的两个实体正确相关。
Lots of examples in the D2 manual. Just keep in mind that query builder works with objects, not sql.
D2手册中有很多例子。请记住,查询构建器适用于对象,而不是 sql。
And by the way, your error message comes from the fact that the entity repository (as opposed to the entity manager) requires an alias.
顺便说一下,您的错误消息来自实体存储库(而不是实体管理器)需要别名的事实。

