[英]Yii::app()->db->createCommand() caching query results?
I'm new to Yii and I have a problem with Yii::app()->db->createCommand()
that I run after inserting a row to table. 我是Yii的新手,并且在向表中插入行后运行的Yii::app()->db->createCommand()
。 I want to check how many rows I have in the table with params supplied, but Yii::app()->db->createCommand()
returns 0 even if the row is inserted. 我想检查表中提供了参数的行数,但是即使插入行, Yii::app()->db->createCommand()
也会返回0。
Here's the simplified code: 这是简化的代码:
$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
Value of exists is 0, but when I run the same query through MySQL workbench I get 1, so I assume there's some built-in caching mechanism that's returning stale data. 存在的值为0,但是当我通过MySQL工作台运行相同的查询时,我的值为1,因此我假设存在一些内置的缓存机制来返回陈旧的数据。
Any thoughts? 有什么想法吗?
Looks like a syntax error, with error reporting off. 看起来像语法错误,但错误报告已关闭。
If you don't pass true
to queryAll, you will NOT get an associative array back; 如果您未将true
传递给queryAll,则不会获得关联数组。 rather, you will get a result with integer index keys. 相反,您将获得带有整数索引键的结果。
In other words, your $count
variable contains: 换句话说,您的$count
变量包含:
$count = array(
0=>array(0=>1)
)
With error_reporting(
) set to 0, $count[0]["num"]
evaluates to false
in this situation. 将error_reporting(
)设置为0,在这种情况下$count[0]["num"]
计算结果为false
。
To solve, pass true
to queryAll()
要解决, queryAll()
true
传递给queryAll()
$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"];
Or use queryScalar()
或使用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;
Or even access the correct array element using your original query: 甚至使用原始查询访问正确的数组元素:
$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];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.