2019-04-17 20:08:45 3125次浏览 1条回答 1 悬赏 10 金钱

Yii2 $model->attributes = $value 保存数据为空,有人遇到过吗?

<?php

namespace app\models;
use yii\db\ActiveRecord;

class Order extends ActiveRecord
{
    public $field1;
    public $field2;
    public $field3; //去掉红色的属性,赋值便不为空了。
    public $field4;
    public $field5; 

    public function rules()
    {
        return [
            [['field1','field2', 'field3', 'field4', 'field5'],'safe'] //=> 注意:必须为 safe【1】
        ];
    }

    /**
     * @return string the name of the table associated with this ActiveRecord class.
     */
    public static function tableName()
    {
        return 'my_table_name';
    }
}

最佳答案

  • 灰太狼 发布于 2019-04-18 09:07 举报

    因为你的 Order 是继承了 ActiveRecord ,而 ActiveRecord 是针对数据表进行映射操作的。
    也就是说,ActiveRecord 的属性赋值都是针对数据表的字段。ActiveRecord 它对应有一个操作的属性数组叫做 $_attribute[]

    $model->attributes = $value; 时候,yii 会去执行 setAttributes()
    给属性赋值,在 setAttributes 方法里给某个属性赋值,如果这个属性不存在会自动调用 __set()
    yii __set() 会把属性和值写到 $_attribute[]
    例如 $_attribute[name] = '小王';
    最后在save的时候会把这个 $_attribute[] 的值写回数据库就实现了保存。

    而你说的 $model->attributes = $value; 为什么没保存到值,上面说了 yii会去执行 setAttributes()
    在给属性赋值的时候如果发现没有这个属性就会去执行__set() 然后写入 $_attribute[]
    很显然你的模型有这个属性,yii就直接给你定一个 publie $fieldX 赋值了。也就是没有走 __set();
    也没有写入 $_attribute[] 在保存的时候 $_attribute[]这里都没有你赋值的这个字段当然保存不聊了。

    如果你想继承ar模型,就不需要自己重新定义字段属性,yii会自动解析数据字段。
    如果你想使用自定义属性就要继承 Model 不要继承 ActiveRecord;

    没有找到数据。
您需要登录后才可以回答。登录 | 立即注册
PHP学院的中学生
副总裁

PHP学院的中学生

注册时间:2018-10-23
最后登录:2024-04-07
在线时长:168小时1分
  • 粉丝29
  • 金钱4730
  • 威望30
  • 积分6710

热门问题