I am trying to create a weighted search using doctrine. This is how i do it in straight sql. Im wondering how i would convert it to us the doctrine2 methods. I am trying to do this search using symfony2.
Also if there is a better way to do this I am open to that to. Thanks.
"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"
Yes, it can be done using DQL
. Doctrine does not support IF
statement. But same functionality can be achieved by CASE
statement. Sample DQL
is given bellow,
$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)
;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With