如何将复杂的MySQL查询转换为Doctrine2

时间:2012-03-20 19:37:09

标签: mysql symfony doctrine-orm

我正在尝试使用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"

1 个答案:

答案 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)
  ;