【发布时间】:2014-06-10 19:20:36
【问题描述】:
我需要将原始查询作为字符串获取,类似这样。
$query = 'SELECT p FROM GabrielUploadBundle:Image p WHERE p.upvotes > x ORDER BY p.createdAt ASC';
我的自定义“findAllNewestByVotes”方法包含查询。
class ImageRepository extends EntityRepository
{
public function findAllNewestByVotes($maxvotes)
{
return $this->getEntityManager()
->createQuery(
'SELECT p FROM GabrielUploadBundle:Image p WHERE p.upvotes > '.$maxvotes.' ORDER BY p.createdAt ASC')
->getResult();
}
}
/**
* @Route("/world/front",name="world-front")
* @Template()
*/
public function indexAction()
{
$images = $this->get('doctrine')->getRepository('GabrielUploadBundle:Image')->findAllNewestByVotes(50);
ladybug_dump($images);
return $this->render('GabrielLayoutBundle:Worldpage:index.html.twig',array('images'=>$images));
}
我需要的是类似的东西 $images->getRawQuery() // 以字符串形式返回查询
解决方案(参考最佳答案)
/**
* ImageRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class ImageRepository extends EntityRepository
{
public function findAllNewestByVotes($maxvotes)
{
return $this->getEntityManager()
->createQuery(
'SELECT p FROM GabrielUploadBundle:Image p WHERE p.upvotes > '.$maxvotes.' ORDER BY p.createdAt ASC');
}
}
> create image repository
$images = $this->get('doctrine')->getRepository('GabrielUploadBundle:Image')->findAllNewestByVotes(50);
return the raw query as string like this
$images->getDQL()
return objects like this
$images->getResult();
【问题讨论】:
-
作为字符串的查询是毫无用处的,除非你考虑将它作为一个丑陋的字符串附加到它上面,因为 Doctrine 在动态构建 SQL 查询方面具有非常易于使用的功能。
-
如果没有用,他们就不会创建 getDQL() 方法(见答案)
-
它对你和我——图书馆的受益者/用户——没用——它对较低级别的工作很有用。
-
也许适合你,但我需要将 getDQL() 方法传递给用于分页的捆绑包
-
这是一个较低级别的集成。 3rd 方捆绑包需要 DQL 真是太愚蠢了……如果他们可以直接使用对象并且他们可以自己从对象中获取字符串,为什么还需要字符串?
标签: symfony doctrine-orm dql doctrine-query