PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, February 27, 2022

[FIXED] performing raw query into query builder in yii2

 February 27, 2022     mysql, php, yii, yii2, yii2-advanced-app     No comments   

Issue

How can I convert this raw query into query builder yii2 as I am getting the record using sub-query:

RAW QUERY:

SELECT *
FROM (
    SELECT DISTINCT `comp`.*,TIMESTAMPDIFF(HOUR,comp.created_date,comp.updated_date) 
    AS hours
    FROM `complaints` `comp`
    INNER JOIN `complaint_log` `comp_log` ON comp_log.`comp_id` = comp.`id`
    WHERE ((comp.name LIKE '%%' OR comp.id LIKE '%%' OR comp.phone_no LIKE '%%') 
    AND DATE(comp.created_date) 
    BETWEEN '2018-01-01' AND '2020-03-20') 
    AND (comp.is_delete = 0)
    ORDER BY `comp`.`id` DESC, `comp`.`created_date` DESC)
    AS cte_name WHERE hours > 120;

Yii2 Query

$query = (new \yii\db\Query())
       ->select('comp.*')
       ->from('complaints comp
       ->distinct()
       ->innerJoin('complaint_log as comp_log', 'comp_log.`comp_id` =comp.`id`')
       ->where($search)
       ->andWhere('comp.is_delete = 0')
       ->orderBy("comp.id DESC")
       ->addOrderBy('comp.created_date DESC');

Solution

Try following code:

$subquery =  (new \yii\db\Query())
        ->select(['comp.*', 'TIMESTAMPDIFF(HOUR, comp.created_date, comp.updated_date) AS hours'])
        ->distinct()
        ->from('complaints comp')
        ->innerJoin('complaint_log comp_log', 'comp_log.comp_id = comp.id')
        ->where(['or',
            ['like', 'comp.name', $search_name],
            ['or',
                ['like', 'comp.id', $search_id],
                ['like', 'comp.phone_no', $search_phone],
            ]
        ])
        ->andWhere('DATE(comp.created_date) BETWEEN :cStart AND :cEnd', [':cStart' => '2018-01-01', ':cEnd' => '2020-03-20'])
        ->andWhere(['comp.is_delete' => 0])
        ->orderBy(['comp.id' => SORT_DESC, 'comp.created_date' => SORT_DESC])
    ;
    $query = (new \yii\db\Query())
        ->select('cte_name.*')
        ->from(['cte_name' => $subquery])
        ->where(['>', 'cte_name.hours', 120])
    ;


Answered By - Murodov Mirjalol
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing