【问题标题】:yii2 calculated 2 value in action createyii2 计算 2 价值在行动创造
【发布时间】:2017-05-31 03:57:14
【问题描述】:

这是我在控制器中创建的操作

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" &gt;= "duration" &amp;&amp; leave_type = "Annual Leave" 然后是 total_leave - duration。并将结果插入到tb_employee中的total_leave。

有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: php model-view-controller yii yii2


    【解决方案1】:

    将 beforeSave 函数添加到如下所示的 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前都会触发。

    【讨论】:

    • 谢谢@irfan 它对我有用。但我想在这个计算中添加限制。例如:total_leave="1" - duration"4",这个结果将是 -3.. 所以我想将结果限制到 -1.. 你有解决方案吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-30
    • 2021-09-18
    • 2011-03-19
    • 2018-03-10
    • 2015-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多