在我的 Yii 应用程序中,我有一个代表 siteconfig
表并有四列的模型:
- 整数
config_id
, - 字符串
键
, - 字符串
值
, - 字符串
update_time
。
我使用Gii创建了一个模型(以确保我不会犯任何错误)。我不会在这里发布完整的代码,因为这是 100% 未经我修改的,由 Gii 生成的标准模型代码。由于我的问题与搜索有关,因此我只发布生成代码的重要部分(search()
方法):
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('config_id',$this->config_id);
$criteria->compare('key',$this->key,true);
$criteria->compare('value',$this->value,true);
$criteria->compare('update_time',$this->update_time,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
我正在尝试在正常的 Yii ActiveRecord 搜索中使用生成的模型,如下所示:
$etona = new SiteConfigurationRecord();
$crit = new CDbCriteria();
$crit->select = "value";
$crit->condition = "key=:key";
$crit->params = array(":key"=>"sitename");
$etona = $etona->find($crit);
但是,没有得到预期的搜索结果,而是出现了一个奇怪的(对我来说)错误:
CDbCommand failed to execute the SQL statement: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'key='sitename' LIMIT 1' at line 1. The SQL statement executed was: SELECT value FROM
siteconfig
t
WHERE key=:key LIMIT 1
我哪里出错了?
最佳答案
您使用 key
作为列名称,它是 reserved word in MySQL 。 Yii 使用 table alias在查询中,但对于保留字用作列名称的情况不采取任何特别注意。所以,你必须自己处理这个问题。
例如:
$etona = new SiteConfigurationRecord();
$crit = new CDbCriteria();
$crit->select = "value";
$crit->condition = "t.key=:key"; // 't' is default alias
$crit->params = array(":key"=>"sitename");
$etona = $etona->find($crit);
这应该可以解决您的问题。
关于ActiveRecord 搜索返回 'Syntax error or access violation' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9835160/