我正在尝试使用doctrine创建加权搜索。这是我在直接sql中的方式。我想知道如何将它转换为我们的doctrine2方法。我正在尝试使用symfony2进行此搜索。
如果有更好的方法可以做到这一点,我愿意这样做。感谢。
"SELECT *,
IF(`name` LIKE "%$searchterm%", 20,
IF(`name` LIKE "%$searchterm%", 10, 0)) +
IF(`address` LIKE "%$searchterm%", 5, 0) +
IF(`city` LIKE "%$searchterm%", 1, 0)
AS `weight`
FROM `table_name`
WHERE
(`name` LIKE "%$searchterm%" OR
`address` LIKE "%$searchterm%" OR
`city` LIKE "%$searchterm%")
ORDER BY `weight` DESC
LIMIT 20"
答案 0 :(得分:17)
是的,可以使用DQL
完成。 Doctrine不支持IF
语句。但CASE
语句可以实现相同的功能。样本DQL
如下所示,
$dql = "SELECT t,
(CASE
WHEN (t.name LIKE :searchterm) THEN 10
ELSE 0
END) +
(CASE
WHEN (t.address LIKE :searchterm) THEN 5
ELSE 0
END) +
(CASE
WHEN (t.city LIKE :searchterm) THEN 1
ELSE 0
END)
AS weight
FROM YourBundleName:TableName t
WHERE
t.name LIKE :searchterm OR
t.address LIKE :searchterm OR
t.city LIKE :searchterm
ORDER BY weight DESC
";
$query = $entityManager->createQuery($dql)
->setFirstResult(0)
->setMaxResults(20)
->setParameter('searchterm' , $searchterm)
;