標籤(空格分隔): php, laravelphp
## 編寫全局做用域 ##
編寫全局做用域很簡單。定義一個實現 Illuminate\Database\Eloquent\Scope 接口的類,並實現 apply 這個方法。 根據你的需求,在 apply 方法中加入查詢的 where 條件:laravel
<?php namespace App\Scopes; use Illuminate\Database\Eloquent\Scope; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Builder; class OrderStatusScopes implements Scope { /** * 把約束加到 Eloquent 查詢構造中。 * * @param \Illuminate\Database\Eloquent\Builder $builder * @param \Illuminate\Database\Eloquent\Model $model * @return void */ public function apply(Builder $builder, Model $model) { $builder->where('status', '=', 2); } } ## 在模型中應用全局做用域 ## /** * 模型的 「啓動」 方法. * * @return void */ protected static function boot() { parent::boot(); //對象添加 static::addGlobalScope(new OrderStatusScopes()); // 匿名添加 [全局做用域] static::addGlobalScope('platform', function (Builder $builder){ $builder->where('platform', '=', 2); }); } ## 移除全局做用域 ## 移除類名方式 OrderModel::withoutGlobalScope(OrderStatusScopes::class)->get(); 移除所有 OrderModel::withoutGlobalScopes()->get(); 移除部分 User::withoutGlobalScopes([ FirstScope::class, SecondScope::class ])->get();
## 在模型中編寫本地做用域 ## 只須要在對應的 Eloquent 模型方法前添加 scope 前綴 /** * 本地做用域 [scope + youActionName] * * @param \Illuminate\Database\Eloquent\Builder $query * @return \Illuminate\Database\Eloquent\Builder */ public function scopeProgram($query) { return $query->where('platform', 1); } /** * 在模型中編寫本地動態做用域 [scope + youActionName] * * @param \Illuminate\Database\Eloquent\Builder $query * @return \Illuminate\Database\Eloquent\Builder */ public function scopeStatus($query, $type) { return $query->where('status', $type); } ## 應用本地做用域 ## OrderModel::Program()->Status(1)->get();