Laravel 8 應(yīng)用全局作用域

2021-07-19 11:32 更新

要將全局作用域分配給模型,需要重寫模型的 booted 方法并使用 addGlobalScope 方法:

<?php

namespace App\Models;

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

class User extends Model
{
    /**
     * 模型的 "booted" 方法
     *
     * @return void
     */
    protected static function booted()
    {
        static::addGlobalScope(new AgeScope);
    }
} 

添加作用域后,對(duì) User::all() 的查詢會(huì)生成以下 SQL 查詢語句:

select * from `users` where `age` > 200 
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)