深入理解 yii2的Active Record
深入理解 yii2的Active Record
yii2 中的 $model->attribute() , $model->attributes , $model->attributes= [...], model->fields(), $model->toArray();
以下依次进行剖析:
1.
$this->attributes()
执行的是model的attributes()方法,返回的数据库的字段数组, yiidbActiveRecord 代码如下:
public function attributes() { return array_keys(static::getTableSchema()->columns); }
执行返回结果示例:
array (size=14) 0 => string "id" (length=2) 1 => string "username" (length=8) 2 => string "password_hash" (length=13) 3 => string "password_reset_token" (length=20) 4 => string "email" (length=5) 5 => string "auth_key" (length=8) 6 => string "status" (length=6) 7 => string "created_at" (length=10) 8 => string "updated_at" (length=10) 9 => string "password" (length=8) 10 => string "role" (length=4) 11 => string "access_token" (length=12) 12 => string "allowance" (length=9) 13 => string "allowance_updated_at" (length=20)
2.
var_dump($this->attributes) 执行的是函数: yiiasemodel->getAttributes(),该函数代码如下
public function getAttributes($names = null, $except = []) { $values = []; if ($names === null) { $names = $this->attributes(); } foreach ($names as $name) { $values[$name] = $this->$name; } foreach ($except as $name) { unset($values[$name]); } return $values; }
也就是说,先通过 $this->attributes()方法,得到数据库表的字段数组
然后 依次遍历,查看各个属性,$this->$name获取各个字段对应的值,而这个访问的是对象的属性,是通过魔术方法__get 从private属性 yiidbBaseActiveRecord::$_attributes 获取的,也就是说数组的结构是先用数据库字段作为数组的key, value是从数组 yiidbBaseActiveRecord::$_attributes中取值
然后拼起来的数组,也就是只有数据库里面的部分,对于model中定义的成员变量和其他的属性,这里是不做输出的。仅仅是数据库的字段部分。
如果您想得到一些定义的成员变量,但是又不想定义fields那么麻烦,您可以通过
$table_attr = $this->attributes(); $public_x = [ "password_repeat"]; $arr = array_merge($table_attr,$public_x ); $model->getAttributes($arr);
返回您想访问的所有的属性和成员变量(注意:我说的属性,指的是不是成员变量的属性。)
魔术方法从 yiidbBaseActiveRecord::$_attributes 中取值,如果不存在,返回null
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
copyright © 2008-2019 入门客AI创业平台 版权所有 备案号:湘ICP备2023012770号