2014-11-01 26 views
1

我是Yii的新手,我在Yii::app()->db->createCommand()上遇到問題,我在向表中插入一行後運行。我想檢查提供參數的表中有多少行,但即使插入行,Yii::app()->db->createCommand()也會返回0。Yii :: app() - > db-> createCommand()緩存查詢結果?

這裏的簡化代碼:

$photo_model = new Photo(); 
$ehp_model  = new EventHasPhoto(); 

$photo_model->setIsNewRecord(true); 
$photo_model->photo_id  = null; 
$photo_model->original_id = $data->id; 

$photo_model->save(); 

$ehp_model->setIsNewRecord(true); 
$ehp_model->event_id = $event_id; 
$ehp_model->photo_id = $photo_model->photo_id; 
$ehp_model->is_approved = ($event_model->moderation == 1 ? -1 : 1); 
$ehp_model->save(); 

$count = Yii::app()->db->createCommand()->select('COUNT(p.photo_id) AS num') 
    ->from('photo AS p') 
    ->join('event_has_photo AS ehp','ehp.photo_id=p.photo_id') 
    ->where('p.original_id="'.$data->id.'" AND ehp.event_id='.$event_id) 
    ->queryAll(); 
$exist = $count[0]["num"]; // exists is 0 

價值的存在是0,但是當我運行通過MySQL的工作臺我得到1相同的查詢,所以我想有一些內置的多數民衆贊成在返回陳舊的數據緩存機制。

有什麼想法?

回答

0

看起來像語法錯誤,錯誤報告關閉。

如果你沒有通過true查詢所有,你不會得到一個關聯數組;相反,你會得到一個整數索引鍵的結果。

換句話說,你$count變量包含:

$count = array(
    0=>array(0=>1) 
) 

隨着error_reporting()設置爲0,$count[0]["num"]計算結果爲false在這種情況下。

來解決,通過truequeryAll()

$count = Yii::app()->db->createCommand()->select('COUNT(p.photo_id) AS num') 
    ->from('photo AS p') 
    ->join('event_has_photo AS ehp','ehp.photo_id=p.photo_id') 
    ->where('p.original_id="'.$data->id.'" AND ehp.event_id='.$event_id) 
    ->queryAll(true); 
$exist = $count[0]["num"]; 

或者使用queryScalar()

$count = Yii::app()->db->createCommand()->select('COUNT(p.photo_id) AS num') 
    ->from('photo AS p') 
    ->join('event_has_photo AS ehp','ehp.photo_id=p.photo_id') 
    ->where('p.original_id="'.$data->id.'" AND ehp.event_id='.$event_id) 
    ->queryScalar(); 
$exist = $count; 

甚至使用原始的查詢訪問正確的數組元素:

$count = Yii::app()->db->createCommand()->select('COUNT(p.photo_id) AS num') 
    ->from('photo AS p') 
    ->join('event_has_photo AS ehp','ehp.photo_id=p.photo_id') 
    ->where('p.original_id="'.$data->id.'" AND ehp.event_id='.$event_id) 
    ->queryAll(); 
$exist = $count[0][0];