集合對象
檢測一個集合是否包含一個鍵(contains)
1
2
|
$roles
= User::find( 1 )->roles; if ($roles->contains( 2 ))
{} |
集合 轉 數組 或 JSON(toArray|toJson)
轉換
1
2
3
4
|
$roles
= User::find( 1 )->roles->toArray(); $roles
= User::find( 1 )->roles->toJson(); //
如果一個集合被轉換爲一個字符串,它將以JSON格式返回 $roles
= (string) User::find( 1 )->roles; |
在轉換中隱藏部分字段
1
2
3
4
5
6
|
class User extends Eloquent
{ //
黑名單 protected $hidden
= array( 'password' ); //
白名單 protected $visible
= array( 'first_name' , 'last_name' ); } |
在轉換中包含虛構的字段
1
2
3
4
5
6
7
|
//
將虛構字段寫入白名單 protected $appends
= array( 'is_admin' ); //
定義虛構字段的訪問器(見下文) public function
getIsAdminAttribute() { return $ this ->attributes[ 'admin' ]
== 'yes' ; } |
遍歷和過濾集合(each|filter)
1
2
|
$roles
= $user->roles->each(function($role){}); $roles
= $user->roles->filter(function($role){}); |
根據一個值排序集合
1
2
3
4
|
$roles
= $roles->sortBy(function($role) { return $role->created_at; }); |
使用自定義集合類,重寫 newCollection 函數
1
2
3
4
5
6
|
class User extends Eloquent
{ public function
newCollection(array $models = array()) { return new CustomCollection($models); } } |
訪問器和調整器
定義一個訪問器(getXxxAttribute)
1
2
3
4
5
6
7
|
class User extends Eloquent
{ //
定義 first_name 字段的訪問器 public function
getFirstNameAttribute($value) { return ucfirst($value); } } |
定義一個調整器(setXxxAttribute)
1
2
3
4
5
6
|
class User extends Eloquent
{ public function
setFirstNameAttribute($value) { $ this ->attributes[ 'first_name' ]
= strtolower($value); } } |
指定哪些字段使用日期調整器(getDates)
1
2
3
4
|
public function
getDates() { return array( 'created_at' ); } |
模型事件
可用事件
creating
created
創建
updating
updated
更新
saving
saved
創建
& 更新
deleting
deleted
刪除
注意: 事件函數中若返回 false
則表示取消本事件。
模型外註冊事件
1
2
3
4
5
|
User::creating(function($user) { //
若無效,則取消創建 if (
! $user->isValid()) return false ; }); |
模型內設置事件綁定
1
2
3
4
5
6
7
8
|
class User extends Eloquent
{ public static function
boot() { //
必須先繼承原生引導方法 boot parent::boot(); //
接下來開始設置事件綁定 } } |
模型觀察者(將一系列的模型事件註冊,寫入有一個類中)
創建模型觀察者
1
2
3
4
|
class UserObserver
{ public function
saving($model){} public function
saved($model){} } |
註冊模型觀察者實例(observe)
1
|
User::observe( new UserObserver); |