數組訪問

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

模型對(dui)象支(zhi)持數組方(fang)式訪問,例如:

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

轉換為數組

可以使用toArray方法將當前的(de)模型實(shi)例輸出為數組,例如(ru):

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

支持設置不輸出的字段屬性:

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

數組(zu)輸出的字(zi)段(duan)(duan)值會經過獲取器的處理(li),也可以支持(chi)追加其它獲取器定義(yi)(不在(zai)數據表(biao)字(zi)段(duan)(duan)列表(biao)中(zhong))的字(zi)段(duan)(duan),例(li)如:

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

支持設置允許輸出的屬性,例(li)如(ru):

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

如果是數據集查詢的話有兩種情況,由于默認的數據集返回結果的類型是一個數組,因此無法調用toArray方法,必須先轉成數據集對象然后再使用toArray方法,系統提供了一個collection助手函數實現數據集對象的轉換,代碼如(ru)下(xia):

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

如(ru)果設置了模型的數據集(ji)返回類型的話,則可以簡化使用

<?php

namespace app\index\model;

use think\Model;

class User extends Model
{
    protected $resultSetType = 'collection';
}

然后就(jiu)可以直接使用(yong)

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

追加關聯模型的屬性(V5.0.4+

V5.0.4+版本(ben)開始,支持追加(jia)一(yi)對一(yi)關聯(lian)模型的屬性到當前(qian)模型,例如(ru):

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

profile是關聯定義方法名,emailnicknameProfile模型的屬性。

支持關聯屬性(V5.0.5+

模型的visiblehiddenappend方(fang)法支持關聯(lian)屬性(xing)操作(zuo),例如:

$user = User::get(1,'profile');
// 隱藏(zang)profile關聯屬(shu)性(xing)的email屬(shu)性(xing)
dump($user->hidden(['profile'=>['email']])->toArray());
// 或者使用(yong)
dump($user->hidden(['profile.email'])->toArray());

hiddenvisibleappend方法同樣支持數據集對(dui)象。