什么是查询作用域
,个人理解是对where条件进行封装,可以优化条件,可以共用条件。
在model
中定义作用域
<?php namespace App;
use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentBuilder;
class Event extends Model
{
protected $table = 'events';
//全局作用域
protected static function boot()
{
parent::boot();
static::addGlobalScope('published', function (Builder $builder) {
$builder->where('published', '>', 0);
});
}
//局部作用域
public function scopePublished($query,$type)
{
return $query->where('published', $type);
}
}
在controller
中使用
//全局作用域
$list = AppEvent::all();
print_r($list->toArray());
//局部作用域
$list = AppEvent::published(1)->get();
print_r($list->toArray());
如有问题,可以QQ搜索群1028468525加入群聊,欢迎一起研究技术
转载请注明:laravel中查询作用域 出自老鄢博客 | 欢迎分享