Yii基于Criteria的SQL查询错误

时间:2013-09-27 07:50:16

标签: sql yii criteria

我想搜索一些模型事件,同时按时和相关用户过滤它们。 我在网格中做它很好。然而,当我另外在网格输入中输入一些数据来搜索Event的其他属性时,ajax响应会: 参数号无效:绑定变量数与令牌数不匹配。 enter image description here “IN条件”(在查询中显示)被添加到标准中:

 $newCriteria = new CDbCriteria;        
 // get events id (several ) of current user
 $events = $model->getEvents($currentUser);
 // add the condition into criteria;  't' being the model table alias
 if ($events) $newCriteria->addInCondition('t.Id', $events); 
 // merge with criteria from the model (DocEvents)
 $newCriteria->mergeWith($model->criteria());

 $dataProvider = new CActiveDataProvider('DocEvents', array(
        'criteria'=>$newCriteria,//$model->criteria(), 
    ));

 $this->widget('bootstrap.widgets.TbGridView', array(
'dataProvider'=>$dataProvider,   
'filter'=>$model,'columns'=>array(
    'Id',
    'Subject',
    'EventTypeId',
    'Begin',
    'End',
    array(
        'class'=>'bootstrap.widgets.TbButtonColumn',
    ),
  ),
));     

模型文件中的标准:

 public function criteria()
{
    $criteria=new CDbCriteria;

    $criteria->compare('Id',$this->Id);
    $criteria->compare('Subject',$this->Subject,true);
    $criteria->compare('Notes',$this->Notes,true);
    $criteria->compare('Place',$this->Place,true);
    $criteria->compare('EventTypeId',$this->EventTypeId,true);
    $criteria->compare('Percentage',$this->Percentage);
    $criteria->compare('ReflectInCalendar',$this->ReflectInCalendar);
    $criteria->compare('ParentId',$this->ParentId);
    $criteria->compare('Priority',$this->Priority);
    $criteria->compare('StatusId',$this->StatusId);
    $criteria->compare('Comment',$this->Comment,true);
    $criteria->compare('PlanHours',$this->PlanHours);
    $criteria->compare('Tags',$this->Tags,true);

    $conditions=array();
    if ($this->Begin) $conditions[] = 'Begin >= "' . $this->Begin . '" ';
    if ($this->End) $conditions[] = 'End <= "' . $this->End . '" ';
    $criteria->condition = implode(' AND ', $conditions);

    return $criteria;
}

如何解决问题?

1 个答案:

答案 0 :(得分:1)

输入附加数据时失败的原因是因为至少使用了一条compare行,这最终构成了条件条件的一部分,同时为该条件绑定了一个参数(又名where子句)。

但是,在criteria()方法结束时,您使用以下行覆盖条件:

$criteria->condition = implode(' AND ', $conditions);

这导致绑定参数,但所有令牌都被覆盖。

因此,请使用

$criteria->addCondition(implode(' AND ', $conditions));

而不是覆盖你已经创建的where子句。

或者,更简单地说,使用以下内容而不是破坏您的$conditions数组。

if ($this->Begin) $criteria->addCondition('Begin >= "' . $this->Begin . '" ';
if ($this->End) $criteria->addCondition('End <= "' . $this->End . '" ');