Php 在Laravel中为模型定义多个全局范围
我有一个具有SoftDelete功能的Post模型和一个active布尔字段来确定Post active状态Php 在Laravel中为模型定义多个全局范围,php,laravel,Php,Laravel,我有一个具有SoftDelete功能的Post模型和一个active布尔字段来确定Post active状态 class Post extends Model implements SluggableInterface { use SoftDeletes; protected $primaryKey = 'post_id'; . . . } 此外,Post模型还有一个start\u date字段,用于保存发布Post的开始日期 现在,我想用它只过滤和
class Post extends Model implements SluggableInterface
{
use SoftDeletes;
protected $primaryKey = 'post_id';
.
.
.
}
此外,Post模型还有一个start\u date
字段,用于保存发布Post的开始日期
现在,我想用它只过滤和获取活动帖子,它们的start\u dat
e为NULL或小于now(),除了非软删除的模型
为此,我将此添加到Post
模型中:
protected static function boot()
{
parent::boot();
static::addGlobalScope('active', function(Builder $builder){
$builder->where('active',1);
});
static::addGlobalScope('scheduled', function(Builder $builder){
$builder
->whereNull('start_date')->orWhere(function ($query) {
$query->where('start_date', '<=', Carbon::now());
});
});
}
受保护的静态功能启动()
{
父::boot();
静态::addGlobalScope('active',函数(Builder$Builder){
$builder->where('active',1);
});
静态::addGlobalScope('scheduled',函数(Builder$Builder){
$builder
->whereNull('start_date')->或where(函数($query){
$query->where('start_date','这是因为您使用的是或where
。在这些情况下,使用Laravel调试栏查看原始SQL非常有用,因为我敢打赌您的select语句如下所示:
从表中选择*,其中deleted_at为NULL,active=1,state_date为NULL或(start_date WHERE(function($query)){
$query->whereNull('start_date');
$query->orWhere('start\u date','
static::addGlobalScope('scheduled', function(Builder $builder) {
$builder->where(function($query)) {
$query->whereNull('start_date');
$query->orWhere('start_date', '<=', Carbon::now());
});
});