我正在尝试在yii应用程序上获取时间范围。
这是我的模型:
public function timeRange($attribute, $params) {
$criteria = new CDbCriteria;
$criteria->addCondition(
"WHERE ('jam_keluar' > '{$this->jam_masuk}' OR 'jam_masuk' < '{$this->jam_keluar}')".
"OR ('jam_masuk' < '{$this->jam_keluar}' AND 'jam_keluar' > '{$this->jam_keluar}')"
);
$record = self::model()->exists($criteria);
if(!empty($record)) {
$this->addError('jd_id', 'Item already exists within range.');
return false;
}
}
但我收到以下错误:
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 'WHERE ('jam_keluar' > 03:00:00' OR 'jam_masuk' < '12:00:00')OR ('jam_masuk' < '1' at line 1. The SQL statement executed was: SELECT 1 FROM `a_jadwal` `t` WHERE WHERE ('jam_keluar' > 03:00:00' OR 'jam_masuk' < '12:00:00')OR ('jam_masuk' < '12:00:00' AND 'jam_keluar' > '12:00:00') LIMIT 1
任何人?
最佳答案
您需要从addCondition中删除“ WHERE”,因为addCondition将为您处理该问题。另外,请用引号将所有值转义,但不要在列名两边加上引号。
您应该为此使用CDbCriteria :: compare或至少将addCondition与params一起使用以避免SQL注入:
// Use the solution with CDbCriteria::addCondition
$criteria->addCondition(
"WHERE (jam_keluar > :jam_masuk OR jam_masuk < :jam_keluar)".
"OR (jam_masuk < :jam_keluar AND jam_keluar > :jam_keluar)",
array(
':jam_masuk' => $this->jam_masuk,
':jam_keluar' => $this->jam_keluar
)
);
// Or use the solution with CDbCriteria::compare
$criteria->compare('jam_keluar', '>'.$this->jam_masuk, false);
$criteria->compare('jam_masuk', '<'.$this->jam_keluar, false, 'OR');
$criteria->compare('jam_masuk', '<'.$this->jam_keluar, false, 'OR');
$criteria->compare('jam_keluar', '>'.$this->jam_keluar, false);