首頁  >  文章  >  後端開發  >  Laravel 中的全域範圍(StepWise)。

Laravel 中的全域範圍(StepWise)。

Barbara Streisand
Barbara Streisand原創
2024-09-24 06:20:32503瀏覽

Global Scope in Laravel (StepWise).

全域範圍是 Laravel 中的重要概念,可以在整個應用程式中重複使用 Eloquent 條件。透過實作全域範圍,您可以將特定條件套用到所有模型的查詢,從而促進程式碼重複使用和一致性。相比之下,局部範圍僅限於單一模型。在本教程中,我們將重點介紹在 Laravel 中創建和利用全域範圍。

  1. 在這一步驟中,我們將在 應用程式/範圍/ActiveScope
<?php

namespace app\Scopes;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;

class ActiveScope implements Scope
{
    public function apply(Builder $builder, Model $model)
    {
        // Define your global condition here
        $builder->where('is_active', '=', '1');

        //or we can write
        $builder->whereIsActive('1');

    }
}
  1. 現在在使用者模型中定義 ActiveScope。我們應該重寫給定模型的 boot 方法並使用 addGlobalScope 方法:
<?php

namespace App;

use App\Scopes\AgeScope;
use Illuminate\Database\Eloquent\Model;
use App\Scopes\ActiveScope;

class User extends Model
{
    /**
     * The "booting" method of the model.
     *
     * @return void
     */
    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope(new ActiveScope);
    }
}

在模型中新增 ActiveScope 後,User::all() 將產生以下 SQL。

select * from `users` where `is_active` = '1'

在某些情況下,您可能希望在不套用全域範圍的情況下取得所有資料。在 Laravel 中,您可以使用 withoutGlobalScope 方法繞過全域作用域並取得所有資料。

User::withoutGlobalScope(ActiveScope::class)->get();

如果你想刪除應用於模型的多個或全部全域作用域,可以使用 Laravel 中的 withoutGlobalScopes 方法。此方法可讓您繞過所有全域範圍或指定要刪除的範圍。這是一個例子:

// Remove all of the global scopes...
User::withoutGlobalScopes()->get();
// Remove some of the global scopes...
User::withoutGlobalScopes([
    ActiveScope::class, AgeScope::class
])->get();

如果您喜歡這些內容並想支持更多精彩的文章,請考慮為我買杯咖啡! ☕️?您的支持對我來說意味著整個世界,並有助於保持知識的流動。您可以在這裡執行此操作:?請我喝杯咖啡

以上是Laravel 中的全域範圍(StepWise)。的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn