yii如何简化检查存在然后插入

时间:2013-12-19 03:52:47

标签: yii

当数据不存在时,我使用Yii 1插入数据。

$email = 'xx@xx';
if( ! people::model()->exists("email = :email", array(':email'=>$email) ){
     $people = new people();
     $people->email = $email;

     $people->xx = xx 
     // ... save
}

我想写这样的,简化和快速:

$people = new people();
$people->email = $email;
if( ! $people->exists() ){
     $people->xx = xx 
     // ... save
}

剂量yii CActiveRecord有办法做到这一点还是需要我扩展CActiveRecord?

3 个答案:

答案 0 :(得分:3)

简单地说,您可以在模型规则中使用unique验证程序。

public function rules()
{        
    return array(
        array('field1,field2, field3, email, field4', 'required'),
        array('email', 'email','message'=>'Invalid email.'),
        array('email', 'unique', 'message' => 'Email already exists!'),
        ...................
        ...................

}            

答案 1 :(得分:2)

Yii对复合唯一键验证有限制。点击此处:http://www.yiiframework.com/forum/index.php/topic/15622-composite-unique-key-validation/ http://www.yiiframework.com/forum/index.php/topic/10154-unique-validator-criteria/

因此,我建议采用这种独特的验证方式。

在规则中,

array('username', 'validateUniqueUsername'),

然后是方法定义。

public function validateUniqueUsername($attribute, $params)
{
    $validator = new CUniqueValidator();
    $validator->attributes = array($attribute);
    $validator->validate($this, array($attribute));
    if ($this->hasErrors($attribute)) {
        $this->clearErrors($attribute);
        $this->addError('username', Yii::t('auth', 'Username "'.$this->username.'" has already been taken.'));
    }
}

参考:http://www.yiiframework.com/doc/api/1.1/CUniqueValidator

答案 2 :(得分:0)

是的,Yii在CActiveRecord中确实有一个exists方法。您只需指定条件,并调用exists(),您的模型将返回是否存在满足这些条件的记录。

Yii CActiveRecord exists() method details can be found here.

除了在特定模型的定义中执行的典型方法之外,您不需要扩展CActiveRecord。