我需要将原始查询作为字符串获取,类似这样。
$ 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();
答案 0 :(得分:3)
可以使用以下方法检索原始查询:
$this->getEntityManager()
->createQuery('
SELECT p
FROM GabrielUploadBundle:Image p
WHERE p.upvotes > '.$maxvotes.'
ORDER BY p.createdAt ASC
')
->getSQL();
但这是一个简单的查询,为什么不使用DQL并单独添加参数(使用预防SQL注入攻击的预处理语句)?
$this->getEntityManager()
->createQueryBuilder()
->select('p')
->from('GabrielUploadBundle:Image')
->where('p.upvotes > :maxvotes')
->setParameter('maxvotes', $maxvotes)
->orderBy('p.createdAt', 'ASC')
->getSQL();
为了能够从控制器获取查询(对象)或查询构建器(对象),您需要将存储库逻辑分解为2个函数,一个构建查询,另一个使用参数调用查询:
class ImageRepository extends EntityRepository
{
public function findAllNewestByVotesQuery($maxvotes)
{
return $this->getEntityManager()
->createQueryBuilder()
->select('p')
->from('GabrielUploadBundle:Image')
->where('p.upvotes > :maxvotes')
->setParameter('maxvotes', $maxvotes)
->orderBy('p.createdAt', 'ASC');
}
public function findAllNewestByVotes($maxvotes)
{
return $this
->findAllNewestByVotesQuery($maxvotes)
->getQuery()
->getResult();
}
}