REST API 的用户名和电子邮件检查

Username and email check for REST API

我是 php 开发的新手。我创建了一个 REST API,其中创建了 employees 并生成了员工列表。检查 API 的工具是 postman

现在我想做的是,当输入用户名和电子邮件时,它会检查它们,如果用户名和电子邮件已经被占用,那么它不会创建而不是给出错误消息。

作为php的新手,我找不到完美的例子。下面是代码

员工模型

class Employee extends \yii\db\ActiveRecord
{
const SCENARIO_CREATE = 'create';
/**
 * @inheritdoc
 */
public static function tableName()
{
    return 'employee';
}

/**
 * @inheritdoc
 */
public function rules()
{
    return [
        [['emp_name', 'emp_email', 'emp_sal'], 'required'],
        [['emp_name', 'emp_email', 'emp_sal'], 'string', 'max' => 100],
    ];
}


public function scenarios()
{
    $scenarios = parent::scenarios();
    $scenarios['create'] = ['emp_name','emp_email', 'emp_sal'];
    return $scenarios;

}

/**
 * @inheritdoc
 */
public function attributeLabels()
{
    return [
        'id' => 'ID',
        'emp_name' => 'Emp Name',
        'emp_email' => 'Emp Email',
        'emp_sal' => 'Emp Sal',
    ];
}

员工控制器

 public function actionCreateEmployee()
{


   \Yii::$app->response->format= \yii\web\Response::FORMAT_JSON;


    $employee = new Employee();
    $employee-> scenario = Employee::SCENARIO_CREATE;

    $employee->attributes = \Yii::$app->request->post();

    if ($employee->validate())
    {
        $employee->save();
        return array('status'=> true, 'data' => 'Employee Created Sussessfully');
    }
    else
    {
        return array('status'=> false, 'data'=>$employee->getErrors());
    }
    //return array('status'=> true);
}

public function actionListEmployee()
{
    \Yii::$app->response->format= \yii\web\Response::FORMAT_JSON;

    $employee = Employee::find()->all();

    if(count($employee)>0)
    {
        return array('status' => true,'data'=> $employee);
    }
    else{
        return array('status'=>false, 'data'=> 'No Employee Record Found');
    }

}

ID 自动递增。

非常感谢任何帮助。

Yii2 具有唯一性验证。要实现这一点,您必须将其添加到要检查唯一性的字段的规则数组中。在您的情况下,这将如下所示:

public function rules()
{
    return [
        [['emp_name', 'emp_email', 'emp_sal'], 'required'],
        [['emp_name', 'emp_email', 'emp_sal'], 'string', 'max' => 100],
        [['emp_email'],'unique','message'=>'Employee email has already been taken. Use another email.'],
        [['emp_name'],'unique','message'=>'User name has already been taken.']
    ];
}

如果你想了解更多关于 Yii2 的唯一验证器,你可以查看这个linkhttp://www.yiiframework.com/doc-2.0/yii-validators-uniquevalidator.html