數(shù)組訪問

版本 新增功能
5.0.10 增加removeRelation方法去除所有的關(guān)聯(lián)屬性
5.0.5 hidden、visibleappend方法支持關(guān)聯(lián)屬性
5.0.4 增加appendRelationAttr方法追加關(guān)聯(lián)模型的屬性

模型對象支持數(shù)組方式訪問,例如:

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

轉(zhuǎn)換為數(shù)組

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

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

支持設(shè)置不輸出的字段屬性:

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

數(shù)組輸出的字段值會經(jīng)過獲取器的處理,也可以支持追加其它獲取器定義(不在數(shù)據(jù)表字段列表中)的字段,例如:

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

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

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

如果是數(shù)據(jù)集查詢的話有兩種情況,由于默認的數(shù)據(jù)集返回結(jié)果的類型是一個數(shù)組,因此無法調(diào)用toArray方法,必須先轉(zhuǎn)成數(shù)據(jù)集對象然后再使用toArray方法,系統(tǒng)提供了一個collection助手函數(shù)實現(xiàn)數(shù)據(jù)集對象的轉(zhuǎn)換,代碼如下:

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

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

<?php

namespace app\index\model;

use think\Model;

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

然后就可以直接使用

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

追加關(guān)聯(lián)模型的屬性(V5.0.4+

V5.0.4+版本開始,支持追加一對一關(guān)聯(lián)模型的屬性到當前模型,例如:

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

profile是關(guān)聯(lián)定義方法名,emailnicknameProfile模型的屬性。

支持關(guān)聯(lián)屬性(V5.0.5+

模型的visible、hiddenappend方法支持關(guān)聯(lián)屬性操作,例如:

$user = User::get(1,'profile');
// 隱藏profile關(guān)聯(lián)屬性的email屬性
dump($user->hidden(['profile'=>['email']])->toArray());
// 或者使用
dump($user->hidden(['profile.email'])->toArray());

hidden、visibleappend方法同樣支持數(shù)據(jù)集對象。