如何使用Yii2检查数据库中是否存在数据?

时间:2017-03-06 17:27:43

标签: php web yii yii2

我正在学习Yii2,我正在尝试在我的Yii基础项目中进行注册。问题是我无法检查数据库中用户输入(在我的情况下是电子邮件和网址)中是否存在某些数据,以便为每个用户制作一个唯一的电子邮件。

public function actionRegistration()
{
    $model = new RegistrationForm();

    if ($model->load(Yii::$app->request->post()) && $model->validate())
    {           
        if (Users::findOne($model->email) !== null)//Doesn't work
            $error_email = "That email is taken. Try another.";
        if (Users::findOne($model->url) !== null)//Doesn't work
            $error_url = "That url is taken. Try another.";

        if (!(isset($error_email) || isset($error_url)))
        {
            $db = new Users();
            $db->name = $model->name;
            $db->email = $model->email;
            $db->password = $model->password;
            $db->url = $model->url;
            $db->save();
        }
        else
        {
            return $this->render('registration',
                    [
                        'model' => $model,
                        'error_email' => $error_email,
                        'error_url' => $error_url,
                    ]
                );
        }
    }
    else
    {
        return $this->render('registration',
                [
                    'model' => $model,
                ]
            );
    }
}

3 个答案:

答案 0 :(得分:3)

findOne()基于您应该使用的主键(简称id)

Users::findOne(['email' => $model->email]);

或更好

Users::find()->where(['email' => $model->email])->one();

one()返回模型

你也可以使用exists()

Users::find()->where(['email' => $model->email])->exists(); 

返回布尔值

答案 1 :(得分:2)

Users::find()->where(['email' => $model->email])->exists();

答案 2 :(得分:2)

简单的方法是在模型中设置验证规则。

型号:

class RegistrationForm extends \yii\db\ActiveRecord  {

...

public function rules(){
    return [
        ['email', 'filter', 'filter' => 'trim'],
        ['email', 'email'],
        ['email', 'unique', 'targetClass' => '\common\models\Users', 'message' => 'This address is use.'],
    ];
}

和控制器

public function actionRegistration() {
$model = new RegistrationForm();

if ($model->load(Yii::$app->request->post()) && $model->validate()) {           

        $db = new Users();
        $db->name = $model->name;
        $db->email = $model->email;
        $db->password = $model->password;
        $db->url = $model->url;
        $db->save();
} else {

    return $this->render('registration',
            [
                'model' => $model,
            ]
        );
}

}

Magic在$ model-> validate()

http://www.yiiframework.com/doc-2.0/guide-input-validation.html

http://www.yiiframework.com/doc-2.0/yii-validators-validator.html

您的示例会导致循环请求和响应所有数据。 $ model->通过ajax验证检查并阻止发送请求php数据。