在laravel模型中的scope范围查询之查询作用域
本文简单了解一下laravel Scope的全局范围、本地范围、动态作用域等使用示例代码
全局范围
让我们在app/Scopes/HasActiveScope.php文件中创建一个新的类, 内容如下
<?php
namespace App\Scopes;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
class HasActiveScope implements Scope
{
/**
* Apply the scope to a given Eloquent query builder.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @param \Illuminate\Database\Eloquent\Model $model
* @return void
*/
public function apply(Builder $builder, Model $model)
{
$builder->where('active', true);
}
}
你应该覆盖模型的booted方法并调用模型的addGlobalScope方法。
addGlobalScope 方法接受你的作用域的一个实例作为它的唯一参数
<?php
namespace App\Models;
use App\Scopes\HasActiveScope;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* The "booted" method of the model.
*
* @return void
*/
protected static function booted()
{
// using seperate scope class
static::addGlobalScope(new HasActiveScope);
// you can do the same thing using anonymous function
// let's add another scope using anonymous function
static::addGlobalScope('delete', function (Builder $builder) {
$builder->where('deleted', false);
});
}
使用全局范围
# fetching all active and non-deleted users
$users = User::all();
# above query will result in following sql
select * from `users` where `active` = 1 and `deleted` = 0
从查询中删除范围
你可能不希望你的全局过滤器被应用。例如,如果你想获取所有的用户,无论他们是否处于活动状态。
在这种情况下,你可以用下面的例子删除你应用的范围
# fetch all users weather they are active or not
$users = User::withoutGlobalScope(new HasActiveScope)->all();
# fetch active users weather they are deleted or not
User::withoutGlobalScope('delete')->all();
本地范围
本地作用域是以Scope关键字为前缀的。在这种情况下,你可以在你的Laravel模型中添加本地作用域,而不是定义全局作用域,如下所示
<?php
namespace App\Models;
use App\Scopes\HasActiveScope;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function scopeActive($query)
{
return $query->where('active', 1);
}
public function scopeDelete($query)
{
return $query->where('delete', 0);
}
}
使用本地范围
# apply active local scope to following query
$users = User::active()->orderBy('created_at')->get();
# apply delete local scope to following query
$users = User::delete()->orderBy('created_at')->get();
动态作用域
有时你可能想给你的局部作用域传递额外的参数。在这种情况下,我们可以向我们的局部作用域传递动态参数,它将作为动态作用域。
<?php
namespace App\Models;
use App\Scopes\HasActiveScope;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function scopeActive($query)
{
return $query->where('active', 1);
}
public function scopeDelete($query)
{
return $query->where('delete', 0);
}
public function scopeWithRole($query, $role)
{
return $query->where('role', $role);
}
}
使用动态作用域
# find active users with role admin
$users = User::active()->withRole('admin')->all();
我希望对你有所帮助!
相关文章