In my Yii application, I have a model that represents siteconfig
table and have four columns:
- integer
config_id
, - string
key
, - string
value
, - string
update_time
.
I created a model using Gii (to ensure that I will not make any mistakes). I don't publish entire code here, cause this is 100% unmodified by me, standard model code generated by Gii. Since my problem is related to search, I only publish important part of generated code (the search()
method):
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,
));
}
I'm trying to use generated model in normal Yii ActiveRecord search like that:
$etona = new SiteConfigurationRecord();
$crit = new CDbCriteria();
$crit->select = "value";
$crit->condition = "key=:key";
$crit->params = array(":key"=>"sitename");
$etona = $etona->find($crit);
But, instead of getting expected search results, a strange (for me) error occurs:
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
Where did I go wrong?
As @Dmitry explained, SQL doesn't allow you to use the column name
key
. The Yii call in the code in your answer works because Yii performs parameter binding automatically, using names other than reserved words for the parameters. And it also uses fully-qualified column names (prefixes all column name references with<tablename>.
, regardless of what invalid column name (reserved words) you pass thefindByAttributes
method.now it works.. ^^
i just use this code...
maybe i need to study activerecord more somehow...
but still i don't know why the code above doesn't work
You used
key
for column name, which is a reserved word in MySQL. Yii uses table alias in queries, but does not take any special care in case of reserverd word used as columns names. So, you have to take care of this by yourself.For example:
This should solve your problem.