Yii2.0 下的 load() 方法的使用

一 問題php

最近在使用 Yii2.0,遇到一個 bug:在 /models/OrderDetail.php add() 方法中調用 load() 方法加載數據,卻加載不了。瀏覽器

public function add($data)
{
    if ($this->load($data) && $this->save()) {
        return true;
    }
    return false;
}

二 排錯this

2.1 將 add() 方法修改爲以下(添加 $this->getErrors()):spa

public function add($data)
{
    if (!$this->load($data) ) {
        var_dump($this->getErrors()); echo 'load'; exit;
    }
    if (!$this->save() ) {
        var_dump($this->getErrors()); echo 'save'; exit;
    }
    return false;
}

瀏覽器顯示 "array(0){}load"。說明確實是 load() 方法加載不了數據。code

2.2 查看 load() 方法源碼:orm

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;
    } else {
        return false;
    }
}

主要看 formName() 方法。該方法經過類反射返回與模型名對應的表單名。在 load() 方法中,在經過 $this->formName() 得到 $scope 的值後,就會判斷變量 $data[$scope] 是否存在,如果就會返回真,不然返回假。因爲變量 $data[$scope] 確實不存在,因此致使了 bug 的產生。blog

三 解決方法get

3.1 能夠將 add() 方法修改爲以下:源碼

public function add($data)
{
    // OrderDetail 是模型名
    if ($this->load(['OrderDetail' => $data]) && $this->save()) {
      return true;
    }
    return false;
}

3.2 不修改 add() 方法,而是在對應的控制器裏修改傳給模型的 $data,將其修改成 $data['OrderDetail'] = $data; 再將 $data 傳過來就能夠了。it

相關文章
相關標籤/搜索