activerecordyiimysql-error-1064yii-cmodel

ActiveRecord search returns 'Syntax error or access violation' error


In my Yii application, I have a model that represents siteconfig table and have four columns:

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?


Solution

  • 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:

    $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);
    

    This should solve your problem.