CDbCommand Issue

Today I faced a strange behaviour of the CDbCommand class in Yii v1.1.15.

Although I am not pretty much sure whether its a bug or not, so I leave it on the authorities to decide.

What I did is as follows:-


$cmd = Yii::app()->db->createCommand();


$firstResult = $cmd->select('source')

                    ->from(Master::model()->tableName())

                    ->where('id=1')

                    ->queryColumn();

var_dump($firstResult) Gave the desired results as shown below:-

FIRST Result:-


array

(

    'source' => 'Members'

)

Now I created another query and tried to fetch results with the same $cmd variable.


$secondResult = $cmd->select('id')

                    ->from(Master::model()->tableName())

                    ->where('id=2')

                    ->queryRow();

THIS TIME

var_dump($secondResult) DID NOT GIVE THE DESIRED RESULTS.

Instead it gave the same results that were obtained in the first query.

SECOND Result


array

(

    'source' => 'Members'

)

When I tried to research about it I found that

while setting the select,from,where options for the $secondResult in the $_query property of CDbCommand class everything was fine.

[size="5"]Issue:-[/size]

But when it called the queryInternal() to fetch the record, the getText() didn’t try to create the new query using the new options. Instead it used the already existing query.

To resolve this issue I had to use setText(null) to let it create the new query again.


$secondResult = $cmd->setText(null)

                    ->select('id')

                    ->from(Master::model()->tableName())

                    ->where('id=2')

                    ->queryRow();

No Doubt, its a perfect solution for it but do not you think that if its setting the select,from,where options again for the new query then it should also create the new query too and not use the existing one ?

Before building a new query you need to "reset" the previous one - http://www.yiiframework.com/doc/guide/1.1/en/database.query-builder#building-multiple-queries