Laravel-查询作用域

Laravel-查询作用域

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

全局作用域

编写全局作用域

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

<?php
namespace App\Scopes;

use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;

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

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

应用本地作用域

OrderModel::Program()->Status(1)->get();

posted @ 2019-05-31 18:29  TaylorSWMM  阅读(804)  评论(0)    收藏  举报