我的操作在控制器中创建
public function actionCreate()
{
$model = new User();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
数据库:
tb_leave
id
id_employee <fk>
startdate
enddate
duration
leave_type //enum 'annual leave','medical check'
tb_employee
id
name
address
total_leave
逻辑是// if "total_leave" >= "duration" && leave_type = "Annual Leave"
然后是total_leave - duration
。结果在tb_employee
中插入total_leave。
有人可以帮我解决这个问题吗?
答案 0 :(得分:1)
将toSave函数添加到tb_leave模型类,如下所示,并更新total_leave值。
/**
* @inheritdoc
*/
public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
$user = User::find()->where(['id' => this->id_employee])->one();
if($user->total_leave >= this->duration && this->leave_type = "annual Leave"){
$user->total_leave = $user->total_leave - this->duration;
$user->save();
}
return true;
} else {
return false;
}
}
在保存tb_leave之前,每次都会触发此函数。