See The Actual Sql Statement From Cactiverecord

I am going through the blog tutorial, step by step and it is working but one thing I am sort of taking for granted is the SQL methods in CActiveRecord.

I was thinking a great thing that would help me with using CActiveRecord methods is seeing the actual SQL querey that it generates. For example, in the tutorial we generate this function:




class Comment extends CActiveRecord

{

    ......

    public function findRecentComments($limit=10)

    {

        return $this->with('post')->findAll(array(

            'condition'=>'t.status='.self::STATUS_APPROVED,

            'order'=>'t.create_time DESC',

            'limit'=>$limit,

        ));

    }

}



Now, I sort of understand what is going on… We are selecting all the comments, joining the Posts table, and limiting our querey to a limit of 10 and an approved status. We are also ordering them by date descending.

So…




SELECT * FROM `tbl_comment` c 

LEFT JOIN `tbl_post` p ON p.post_id = c.id 

WHERE c.status = 1 AND c.post_id = ## //(whatever post we are viewing)

ORDER BY c.create_time DESC 

LIMIT 10



That’s just my best guess of the query that pops out of that method, but I don’t know.

If there was a way to log the actual executed queries in the debug mode, just to double check and be sure what we programming is right, that would be great!

As an aside, I do think Yii is taking an elegant approach to doing SQL and grabbing data. I am used to writing out my own statements, crafting them so they are just right through multiple tries on the console, and then putting them on my site. So, I am currently on the fence whether I should do my SQL the Yii way or do it my own way. I am thinking for the simple SQL needed that are non-intrusive, I would do it the Yii way. For more advanced queries, I’d do it manually. Any comments on this?

by passing worng table column name in condition you can see the executed sql in CDbException error log

for example

‘condition’=>‘t.statu=’ isntead of ‘condition’=>‘t.status=’

it’s not ideal but it do the job

Haha that certainly worked!

For the record, here is my SQL (formatted a bit on notepad++)


SELECT `t`.`id` AS `t0_c0`,

 `t`.`content` AS `t0_c1`,

 `t`.`status` AS `t0_c2`,

 `t`.`create_time` AS `t0_c3`,

 `t`.`author` AS `t0_c4`,

 `t`.`email` AS `t0_c5`,

 `t`.`url` AS `t0_c6`,

 `t`.`post_id` AS `t0_c7`,

 `post`.`id` AS `t1_c0`,

 `post`.`title` AS `t1_c1`,

 `post`.`content` AS `t1_c2`,

 `post`.`tags` AS `t1_c3`,

 `post`.`status` AS `t1_c4`,

 `post`.`create_time` AS `t1_c5`,

 `post`.`update_time` AS `t1_c6`,

 `post`.`author_id` AS `t1_c7` 

FROM `tbl_comment` `t` 

LEFT OUTER JOIN `tbl_post` `post` ON (`t`.`post_id`=`post`.`id`) 

WHERE (t.status=2) ORDER BY t.create_time DESC 

So my question, at what point does one depart from the CActiveRecord method conciseness and write their SQL manually?