Yii2唯一验证不适用于员工ID和公司ID的组合 以下是我的型号代码。
public function rules()
{
return [
[['company_id', 'role_id'], 'required'],
[['company_id', 'role_id', 'status'], 'integer'],
[['employee_id'], 'string', 'max' => 15],
[['report_to'], 'string', 'max' => 16],
[['id',],'safe'],
['employee_id', 'unique', 'targetAttribute' => ['company_id', 'employee_id'], 'message' => 'The combination of Company ID and Employee ID has already been taken.']
// ['employee_id', 'unique', 'targetAttribute' => ['company_id'], 'message' => 'The combination of Company ID and Employee ID has already been taken.']
];
}'
这是我的控制器代码
$model = new Employee();
//$profile = new Profile();
// $profile->scenario = 'emp_bulk_uplscenariooad';
if($model->load(Yii::$app->request->post())) {
$model->company_id = $userModel->company_id;
$model->employee_id = Yii::$app->request->post()['Employee']['employee_id'];
$model->role_id = Yii::$app->request->post()['Employee']['role_id'];
$model->report_to = Yii::$app->request->post()['Employee']['report_to'];
// print_r(!$model->validate());die();
if($model->save(false)){
}
*************************************************************************
please help me with this.thanks in advance
答案 0 :(得分:0)
您使用
if($model->save(false)){
这意味着不进行验证
尝试使用
if($model->save()){
并且在actioCreate中你应该回想起如果model-> save()失败的渲染创建
public function actionCreate()
{
$model = new Employee();
if($model->load(Yii::$app->request->post())) {
$model->company_id = $userModel->company_id;
$model->employee_id = Yii::$app->request->post()['Employee']['employee_id'];
$model->role_id = Yii::$app->request->post()['Employee']['role_id'];
$model->report_to = Yii::$app->request->post()['Employee']['report_to'];
// print_r(!$model->validate());die();
if($model->save()){
return $this->redirect(['view', 'id' => $model->id]);
}
else {
return $this->render('create', [
'model' => $model,
]);
}
}
答案 1 :(得分:0)
尝试执行编辑器更新,修复了Yii2错误,除了其他情况外,在使用关系数据时绑定到唯一验证器: