Yii:尝试使用带条件的 'uniqe' 规则时出错
Yii: Error when trying to use a 'uniqe' rule with a condition
我正在处理 Yii 1.1x 网站。
我有一个模型,它有一个标题和一个类别 ID。
我试图防止用户在完全相同的类别中输入相同的标题。 (相同标题不同分类即可)
我尝试使用以下规则,但在测试时出现错误(通过在同一类别中输入重复的标题)
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('str_title, id_category', 'required'),
array('str_title', 'unique', 'criteria'=>array(
'condition'=>'`id_category`=:idcategory',
'params'=>array(
':idcategory'=>$this->id_category
)
)),
);
}
如前所述,当我尝试在同一类别中输入重复的标题时,我收到此错误消息:
CDbCommand failed to execute the SQL statement: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined. The SQL statement executed was: SELECT 1 FROM `posts` `t` WHERE (`id_category`=:idcategory) AND (`t`.`str_title`=:ycp0) LIMIT 1
有人知道问题出在哪里吗?
您不应在 rules()
方法中使用属性值,因为它是在设置属性之前调用的:
- 调用
rules()
获取验证器配置。
- 设置属性。
- 运行 验证。
您应该使用现有扩展 (example) 来验证复合键或为此编写自己的验证器(这并不难,通常内联验证器需要 5-10 行代码)。
我正在处理 Yii 1.1x 网站。
我有一个模型,它有一个标题和一个类别 ID。
我试图防止用户在完全相同的类别中输入相同的标题。 (相同标题不同分类即可)
我尝试使用以下规则,但在测试时出现错误(通过在同一类别中输入重复的标题)
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('str_title, id_category', 'required'),
array('str_title', 'unique', 'criteria'=>array(
'condition'=>'`id_category`=:idcategory',
'params'=>array(
':idcategory'=>$this->id_category
)
)),
);
}
如前所述,当我尝试在同一类别中输入重复的标题时,我收到此错误消息:
CDbCommand failed to execute the SQL statement: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined. The SQL statement executed was: SELECT 1 FROM `posts` `t` WHERE (`id_category`=:idcategory) AND (`t`.`str_title`=:ycp0) LIMIT 1
有人知道问题出在哪里吗?
您不应在 rules()
方法中使用属性值,因为它是在设置属性之前调用的:
- 调用
rules()
获取验证器配置。 - 设置属性。
- 运行 验证。
您应该使用现有扩展 (example) 来验证复合键或为此编写自己的验证器(这并不难,通常内联验证器需要 5-10 行代码)。