Laravel-查询作用域

Laravel-查询作用域

标签(空格分隔): php, laravel

全局作用域

## 编写全局作用域 ##

编写全局作用域很简单。定义一个实现 IlluminateDatabaseEloquentScope 接口的类,并实现 apply 这个方法。 根据你的需求,在 apply 方法中加入查询的 where 条件:

<?php
namespace AppScopes;

use IlluminateDatabaseEloquentScope;
use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentBuilder;

class OrderStatusScopes implements Scope
{
    /**
     * 把约束加到 Eloquent 查询构造中。
     *
     * @param  IlluminateDatabaseEloquentBuilder  $builder
     * @param  IlluminateDatabaseEloquentModel  $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 IlluminateDatabaseEloquentBuilder $query
 * @return IlluminateDatabaseEloquentBuilder
 */
public function scopeProgram($query)
{
    return $query->where('platform', 1);
}


/**
 * 在模型中编写本地动态作用域 [scope + youActionName]
 *
 * @param IlluminateDatabaseEloquentBuilder $query
 * @return IlluminateDatabaseEloquentBuilder
 */
public function scopeStatus($query, $type)
{
    return $query->where('status', $type);
}


## 应用本地作用域 ##



OrderModel::Program()->Status(1)->get();
原文地址:https://www.cnblogs.com/yanweifeng/p/10956877.html