我有一个具有SoftDelete功能的Post模型和一个确定Post活动状态的 active 布尔字段。
class Post extends Model implements SluggableInterface
{
use SoftDeletes;
protected $primaryKey = 'post_id';
.
.
.
}此外,post模型还有一个start_date字段,用于保存发布帖子的开始日期。
现在,除了非软删除的模型之外,我还想使用匿名GlobalScope Laravel 5.2来筛选和只获取活跃的帖子,并且他们的start_date是空的或小于现在的()。
为此,我将其添加到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());
});
});
}仅active全局范围就能正常工作,但是当我添加第二个名为scheduled的作用域时,返回所有记录,包括软删除和inActive模型。
有什么问题吗?我不明白
发布于 2016-05-01 13:47:49
这是因为你在使用orWhere。在这些情况下,使用Laravel查看原始SQL非常有用,因为我打赌select语句如下所示:
SELECT * FROM table WHERE deleted_at IS NULL AND active=1 AND state_date IS NULL OR (start_Date <= now())
它将选择任何符合“一个或”标准的内容。
要解决这个问题,您应该让scheduled看起来像这样。
static::addGlobalScope('scheduled', function(Builder $builder) {
$builder->where(function($query)) {
$query->whereNull('start_date');
$query->orWhere('start_date', '<=', Carbon::now());
});
});这将(希望)使您的查询看起来如下:
SELECT * FROM table WHERE deleted_at IS NULL AND active=1 AND (state_date IS NULL OR start_Date <= now())
这就是我认为你想要的。
https://stackoverflow.com/questions/36967286
复制相似问题