laravel--6 eloquent查询作用域

来源:互联网 发布:愚人节整人软件 编辑:程序博客网 时间:2024/06/07 21:53

理解:查询作用域就是给查询添加条件where语句中自动添加一些条件限制
全局作用域:添加作用域后如果使用PhotoModel::all() PhotoModel::get()则会在SQL语句中增加条件限制

本地作用域:给Model类中的方法where条件限制

全局作用域

  1. 首先定义一个实现Illuminate\Database\Eloquent\Scope接口的类,该接口需要实现apply方法
    eg:
    <?php        namespace App\Scopes;        use Illuminate\Database\Eloquent\Scope;        use Illuminate\Database\Eloquent\Model;        use Illuminate\Database\Eloquent\Builder;        class AgeScope implements Scope{            public function apply(Builder $builder, Model $model) {                return $builder->where('age', '>', 200);            }        }
  1. 应用全局作用域(要将全局作用域分配给模型,需要重写给定模型的 boot 方法并使用 addGlobalScope 方法)
    <?php        namespace App;        use App\Scopes\AgeScope;        use Illuminate\Database\Eloquent\Model;        class User extends Model{            protected static function boot(){                parent::boot();                static::addGlobalScope(new AgeScope);            }        }
  1. 添加作用域后,如果使用 User::all() 查询则会生成如下 SQL 语句
    select * fromuserswhereage> 200
  2. 移除全局作用域
    User::withoutGlobalScope(AgeScope::class)->get()

本地作用域

本地作用域允许我们定义通用的约束集合以便在应用中复用。例如,你可能经常需要获取最受欢迎的用户,要定义这样的一个作用域,只需简单在对应 Eloquent 模型方法前加上一个 scope 前缀。
eg:

<?phpnamespace App;use Illuminate\Database\Eloquent\Model;class User extends Model{    /**     * 只包含活跃用户的查询作用域     *     * @return \Illuminate\Database\Eloquent\Builder     */    public function scopePopular($query)    {        return $query->where('votes', '>', 100);    }    /**     * 只包含激活用户的查询作用域     *     * @return \Illuminate\Database\Eloquent\Builder     */    public function scopeActive($query)    {        return $query->where('active', 1);    }}

作用域被定义好了之后,就可以在查询模型的时候调用作用域方法,但调用时不需要加上 scope 前缀,你甚至可以同时调用多个作用域,例如:
$users = App\User::popular()->active()->orderBy('created_at')->get();