yii2 $model->load解读

为什么80%的码农都做不了架构师?>>>   hot3.png

/**
 * 用输入数据填充模型
 * 
 * 这个方法简化了如下的操作:
 * 
 * attributes = $_POST['FormName'];
 *     if ($model->save()) {
 *         // 成功后的处理
 *     }
 * }
 *
 * 上面的代码可以像这样简写:
 *
 * load($_POST) && $model->save()) {
 *     // 成功后的处理
 * }
 * 
 */

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数据,只有两个方法:

1、表单input 的 name 没有使用数组

      这种情况需要指定load第二个参数为空字符串

$model->load($_POST, '');

2、表单input 的 name 使用数组形式提交数据

      假设数组名是hello,即, 那么

// 假设模型的名称刚好也是hello.php,那么不需要指定第二个参数,因为$this->formName()获取的就是模型的名称
$model->load($_POST);

// 假设模型名称不是hello.php, 那么需要指定第二个参数为hello
$model->load($_POST, 'hello');

 

转载于:https://my.oschina.net/sskill/blog/1609651

你可能感兴趣的:(yii2 $model->load解读)