我正在尝试在Symfony中运行如下查询:
SELECT * FROM company
WHERE name LIKE '%$search%'
ORDER BY CASE WHEN name LIKE '$search%' THEN 1
WHEN name LIKE '%$search' THEN 2
WHEN name LIKE '%$search%' THEN 3
END
LIMIT 0,10
createQuery()
和findBy()
似乎有很多限制我想知道是否有办法用Symfony2以这种方式查询数据库?
请注意,公司表也设置为实体。
这是我尝试的,但没有完成我的整个查询:
$this->getDoctrine()
->getRepository('testMyBundle:Company')
->findBy(array(),array(),10,($current-1)*$numItemsPerPage);
我感谢任何建议,提前谢谢!
答案 0 :(得分:1)
我不喜欢这样的解决方案,但应该有效:
// CompanyRepository.php
public function getSth() {
$query = 'your sql query here';
$em = $this->getEntityManager();
$connection = $em->getConnection();
$stmt = $connection->prepare($query);
$stmt->execute();
return $stmt->fetchAll();
}
在你的控制器中:
$this->getDoctrine()
->getRepository('testMyBundle:Company')->getSth();
答案 1 :(得分:1)
此DQL应该有效:
$query = $this->getDoctrine()
->createQuery('
SELECT c
FROM testMyBundle:Company c
WHERE c.name LIKE :search
ORDER BY CASE WHEN c.name LIKE :search THEN 1
WHEN c.name LIKE :search THEN 2
WHEN c.name LIKE :search THEN 3
END
')
->setParameter('search', '%search%')
->setMaxResults(10)
->setFirstResult(0)
->execute()
;