数组访问

版本 新增功能
5.0.10 增加removeRelation方法去除所有的关联属性
5.0.5 hiddenvisibleappend方法支持关联属性
5.0.4 增加appendRelationAttr方法追加关联模型的属性

模型对象支持数组方式访问,例如:

								$user = User::find(1);
									echo
									$user->name ;
									// 有效
									echo
									$user['name']
									// 同样有效
									$user->name =
									'thinkphp';
									// 有效
									$user['name'] =
									'thinkphp';
									// 同样有效
									$user->save();
								
							

转换为数组

可以使用toArray方法将当前的模型实例输出为数组,例如:

								
									$user
									=
									User:
									:find(1); dump($user->toArray());
								
							

支持设置不输出的字段属性:

								
									$user
									=
									User:
									:find(1); dump($user->hidden(['create_time','update_time'])->toArray());
								
							

数组输出的字段值会经过获取器的处理,也可以支持追加其它获取器定义(不在数据表字段列表中)的字段,例如:

								
									$user
									=
									User:
									:find(1); dump($user->append(['status_text'])->toArray());
								
							

支持设置允许输出的属性,例如:

								
									$user
									=
									User:
									:find(1); dump($user->visible(['id','name','email'])->toArray());
								
							

如果是数据集查询的话有两种情况,由于默认的数据集返回结果的类型是一个数组,因此无法调用toArray方法,必须先转成数据集对象然后再使用toArray方法,系统提供了一个collection助手函数实现数据集对象的转换,代码如下:

								$list = User::all();
									if($list) {     $list = collection($list)->toArray(); }
								
							

如果设置了模型的数据集返回类型的话,则可以简化使用

								<?php  namespace app\index\model;  use think\Model;
									
										class
										User
										extends
										Model
									
									{
									protected
									$resultSetType =
									'collection'; }
								
							

然后就可以直接使用

								
									$list
									=
									User:
									:all();
									$list
									=
									$list->toArray();
								
							

追加关联模型的属性(V5.0.4+

V5.0.4+版本开始,支持追加一对一关联模型的属性到当前模型,例如:

								
									$user
									=
									User:
									:find(1); dump($user->appendRelationAttr('profile',['email','nickname'])->toArray());
								
							

profile是关联定义方法名,emailnicknameProfile模型的属性。

支持关联属性(V5.0.5+

模型的visiblehiddenappend方法支持关联属性操作,例如:

								$user = User::get(1,'profile');
									// 隐藏profile关联属性的email属性
									dump($user->hidden(['profile'=>['email']])->toArray());
									// 或者使用
									dump($user->hidden(['profile.email'])->toArray());
								
							

hiddenvisibleappend方法同样支持数据集对象。