【Laravel】 進階EloquentORM – addGlobalScope 全域範圍

LaravelModel 中,於 boot 給予全域的約束

新增全域範圍後,在指定的條件下,ORM查詢將會自動加增 shop_id 的條件

全域範圍

<?php

namespace App\Scopes;

use App\Models\Shop;
use Illuminate\Support\Facades\Auth;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;

class ShopScope implements Scope
{
    /**
     * Apply the scope to a given Eloquent query builder.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $builder
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @return void
     */
    public function apply(Builder $builder, Model $model)
    {
        if (Auth::user() instanceof Shop || request()->isShop()) {
            $modelTableName = $model->getTable();
            return $builder->where('shop_id', optional(Auth::user()->currentTeam)->organization->id);
        }

        return $builder;
    }
}
// Model 的 boot
protected static function boot()
{
    parent::boot();

    static::addGlobalScope(new ShopScope);
}

 

全域範圍 – 給予命名

static::addGlobalScope('active', function(Builder $builder) {
    $builder->where('is_active', '=', 1)
});

排除全域範圍

Order::withoutGlobalScope('actvie')->get();  // 單一
Order::withoutGlobalScope(ActiveScope::class)->get(); // 單一
Order::withoutGlobalScope([ActiveScope::class, DisplayScope::class])->get();  // 多個
Order::withoutGlobalScope()->get();          // 全部

 

但值得注意的是,在未來 Debug 時,要注意 boot 中是否有使用到相關全域範圍!