【问题标题】:In `Yii2` I'm passing model value but its showing as a null在 Yii2 中,我正在传递模型值,但它显示为 null
【发布时间】:2023-02-02 23:57:09
【问题描述】:

有我的控制器代码

 if ($this->request->isPost) {
            $model->created_by = Yii::$app->user->identity->id;
            $model->created_at = date('Y/m/d');
            // echo $model->created_at;die;
            if ($model->load($this->request->post()) && $model->save()) {
                return $this->redirect(['index', 'id' => $model->id]);
            }
        } 

并且有我的模型规则

public function rules()
{
    return [
        [['deduction_type'], 'required'],
        [['created_at'], 'safe'],
        [['created_by'], 'integer'],
        [['deduction_type'], 'string', 'max' => 100],
    ];
}

我的问题是,每次我将 created_at 和 created_at 数据中的值作为空值保存在数据库中时。 我想要我在 db 中的实际值。

【问题讨论】:

  • $model->created_at = date('Y-m-d');更改为数据库表日期格式为Y-m-d。那么只有safe 会起作用。
  • @Anant-Alivetodie 正如你所说我尝试了 date('Y-m-d') 也尝试了 date('Y-m-d H:i:s') 但最后它在 db 中传递了 Null 值

标签: php yii2


【解决方案1】:

而不是你的方式

 if ($this->request->isPost) {
            //Move that two Lines inside the if
            $model->created_by = Yii::$app->user->identity->id;
            $model->created_at = date('Y/m/d');

            // echo $model->created_at;die;
            if ($model->load($this->request->post()) && $model->save()) {
                return $this->redirect(['index', 'id' => $model->id]);
            }
        }

我通常会做以下事情:

 if ($this->request->isPost) {
            if ($model->load($this->request->post()) && $model->validate()) {
                $model->created_by = Yii::$app->user->identity->id;
                $model->created_at = date('Y/m/d');
                $model->save();
                return $this->redirect(['index', 'id' => $model->id]);
            }
        }

validate()->根据您的规则检查输入是否正确。 之后您知道条目是正确的并且您可以设置您的值。
这是我解决这个问题的常用方法。 您还可以用 if 包装 $model->save(); 以检查您的更改以及捕获潜在的 falseof save()。

【讨论】:

    【解决方案2】:

    检查您的 POST,它是否发送空字段 created_at 和 created_by?不要在 post 中发送此字段,并且 load() 方法不会将其替换为空值。

    【讨论】:

    • 您的答案可以通过其他支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写出好的答案的信息in the help center
    • 我被检查但数据不为空
    【解决方案3】:

    如果您真的想插入当前用户 ID 和当前时间,请使用 BlameableBehavior 和 TimestampBehavior。

    BlameableBehavior 自动使用当前用户 ID 填充指定的属性。 https://www.yiiframework.com/doc/api/2.0/yii-behaviors-blameablebehavior

    TimestampBehavior 自动用当前时间戳填充指定的属性。 https://www.yiiframework.com/doc/api/2.0/yii-behaviors-timestampbehavior

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-23
      • 2021-04-28
      • 1970-01-01
      • 1970-01-01
      • 2021-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多