think-orm icon indicating copy to clipboard operation
think-orm copied to clipboard

模型的`data()`方法调用之后,之前的赋值丢失

Open augushong opened this issue 4 years ago • 0 comments

模型的data()方法,建议不要直接用参数$data赋值到$this->data 上,这样会导致调用data()方法之前的赋值丢失. vendor\topthink\think-orm\src\model\concern\Attribute.php

   public function data(array $data, bool $set = false, array $allow = [])
    {
        // 清空数据
        $this->data = [];

        // 废弃字段
        foreach ($this->disuse as $key) {
            if (array_key_exists($key, $data)) {
                unset($data[$key]);
            }
        }

        if (!empty($allow)) {
            $result = [];
            foreach ($allow as $name) {
                if (isset($data[$name])) {
                    $result[$name] = $data[$name];
                }
            }
            $data = $result;
        }

        if ($set) {
            // 数据对象赋值
            $this->setAttrs($data);
        } else {
            // $this->data = $data;
            $this->data = array_merge($this->data,$data);   // 希望能改成这种写法
        }

        return $this;
    }

augushong avatar Sep 27 '21 15:09 augushong