Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
642 views
in Technique[技术] by (71.8m points)

symfony - How to convert a complex MySQL Query to Doctrine2

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"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...