foreach不在cdbcriteria中工作

时间:2015-09-08 09:07:07

标签: php yii criteria

在我的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无法执行SQL语句:SQLSTATE [42000]:语法错误或访问冲突:1064 SQL语法中有错误;检查与MySQL服务器版本对应的手册,以便在

附近使用正确的语法
') AND (t.courseid= 6 OR )) AND (t.courseid= 7 OR )) AND (t.courseid= 9 OR ))' at line 1. 
  

执行的SQL语句是:

 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 )).

我做错了什么?

1 个答案:

答案 0 :(得分:1)

试试这个

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