foreach 在 cdbcriteria 中不起作用

foreach is not working in cdbcriteria

在我的 Yii 网络应用程序中,foreach 在 cdbcriteria 中不工作

$criteria = new CDbCriteria;
$assignclass = Assignclass::model()->findAllByAttributes(array('usertypeid' => Yii::app()->user->usertypeid));
foreach ($assignclass as $assign) {
    $criteria->addCondition('t.courseid= '.$assign->courseid.' OR ');
}

使用此代码会发生 CDbException 错误,例如,

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

') AND (t.courseid= 6 OR )) AND (t.courseid= 7 OR )) AND (t.courseid= 9 OR ))' at line 1. 

The SQL statement executed was:

 SELECT COUNT(DISTINCT `t`.`studentid`) FROM `student` `t` LEFT OUTER JOIN `course` `course` ON (`t`.`courseid`=`course`.`courseid`) LEFT OUTER JOIN `batch` `batch` ON (`t`.`batchid`=`batch`.`batchid`) WHERE ((((t.courseid= 5 OR ) AND (t.courseid= 6 OR )) AND (t.courseid= 7 OR )) AND (t.courseid= 9 OR )).

我做错了什么?

试试这个

$criteria = new CDbCriteria;
$assignclass = Assignclass::model()->findAllByAttributes( array('usertypeid' => Yii::app()->user->usertypeid));
$cond = '';
foreach ($assignclass as $assign) {
    if($cond == '')
        $cond = 't.courseid= '.$assign->courseid;
    else
        $cond .= ' OR t.courseid= '.$assign->courseid;
}
if($cond != '')
    $criteria->condition = $cond;