Search code examples
sqlyiiranking

yii custom query and CSqlDataProvider


Could someone let me know how to run this query with CSqlDataProvider(yii framework (php ))

SET @rank=0;
SELECT @rank:=@rank+1 AS rank, fruit, amount


FROM sales
 ORDER BY amount DESC
;

and I can do it like below , but

$sqlProvider = new CSqlDataProvider('
SELECT @rank:=@rank+1 AS rank, nameAndFam
  FROM user
');

cant initialise SET @rank=0; before above command ..

I want to rank my select and I think its the good way thanks in advance for your reply :)


Solution

  • You may try to use YII createcommnd from Database Access OBject (DAO) which will provide lowest level of working with database which you can create any queries from any kinds.

    $sql1 = 'SET @rank=0;';
    $sql2 = 'SELECT @rank:=@rank+1 AS rank, fruit, amount
        FROM sales
         ORDER BY amount DESC';
    $cmd1 = Yii::app()->db->createCommand($sql1);
    $cmd2 = Yii::app()->db->createCommand($sql2);
    
    $cmd1->execute();
    $result = $cmd2->query();
    

    after that you can use a foreach loop to loop through the object array returned from this query

    you can create create separate function such as:

    $cmd->select ='SELECT @rank:=@rank+1'; 
    

    that way will make the code so much readable but since you only needed to have this work I only provided you the pure, not optimized way. Hope this may help you work it out.