YII2对于$model->load($data)后没有数据的问题进行处理

YII2对于$model->load($data)后没有数据的问题进行处理

yii2中使用$model->load($data)后出现$model中问题,原因在于$data中没有给出模型名称
出错代码:

$data = [
    'name' => 'test',
    'password' => 'test123456',
];
$model = new User();
$model->load($data);
if ($model->validate()) {
    $model->save();
}

yii2中load()方法的具体实现:

/**
 * Populates the model with input data.
 *
 * This method provides a convenient shortcut for:
 *
 * ```php
 * if (isset($_POST['FormName'])) {
 *     $model->attributes = $_POST['FormName'];
 *     if ($model->save()) {
 *         // handle success
 *     }
 * }
 * ```
 *
 * which, with `load()` can be written as:
 *
 * ```php
 * if ($model->load($_POST) && $model->save()) {
 *     // handle success
 * }
 * ```
 *
 * `load()` gets the `'FormName'` from the model's [[formName()]] method (which you may override), unless the
 * `$formName` parameter is given. If the form name is empty, `load()` populates the model with the whole of `$data`,
 * instead of `$data['FormName']`.
 *
 * Note, that the data being populated is subject to the safety check by [[setAttributes()]].
 *
 * @param array $data the data array to load, typically `$_POST` or `$_GET`.
 * @param string $formName the form name to use to load the data into the model.
 * If not set, [[formName()]] is used.
 * @return bool whether `load()` found the expected form in `$data`.
 */
public function load($data, $formName = null)
{
    $scope = $formName === null ? $this->formName() : $formName;
    if ($scope === '' && !empty($data)) {
        $this->setAttributes($data);

        return true;
    } elseif (isset($data[$scope])) {
        $this->setAttributes($data[$scope]);

        return true;
    }

    return false;
}

由上代码可以看出,当使用load()方法时如果不传递$formName参数时,在$data中应指定表名,此时代码格式应该如下:

$data = [
    'User' => [
        'name' => 'test',
        'password' => '123456'
    ]
];

或手动传递给$formName参数一个空字符串:$model->load($data, '');
亦或者直接使用$model->setAttributes($data);$model->->attributes = $data;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值