首页 文章

Laravel Eloquent查询生成器默认条件

提问于
浏览
7

我有新闻模型,当我查询新闻时,我希望它带来状态= 1的新闻作为默认值 .

News::all(); // select * from news where status = 1
News::where('anotherColumn',2)->get(); // select * from news where status = 1 and where category = 2

这可能吗?我想要的是如此类似于软删除功能(它得到的地方,deleted_at不为null,如果所有数据都需要withTrashed函数可以使用) .

我看了文档,但我找不到任何有用的东西 . 此外,我试图在新闻模型的构造中处理它,但它也没有工作 .

谢谢 .

3 回答

  • 6

    我通常会为此覆盖 newQuery() . newQuery() 是Eloquent用于构造新查询的方法 .

    class News extends Eloquent {
    
        public function newQuery($excludeDeleted = true) {
            return parent::newQuery($excludeDeleted)
                ->where(status, '=', 1);
        }
    
    }
    

    现在你的 News::all() 只输出status = 1的新闻 .

  • 19

    我认为你会得到关闭,而不会真正改变一些核心文件......

    是查询范围......

    通过范围,您可以轻松地在模型中重复使用查询逻辑 . 要定义范围,只需在模型方法前加上范围:

    class News extends Eloquent {
       public function scopeStatus($query)
        {
         return $query->where('status', '=', 1);
        }
     }
    

    利用该范围

    $news  = News::status()->get();
     $news2  = News::status()->where('anotherColumn',2)->get();
    

    它不是你想要的......但它肯定比打字短一点

    News::where('status','=',1)->get();
    

    一遍又一遍

  • 2

    它已经被提及但是这里有一个使用全局范围的快速示例,它可能是当前最好的解决方案,因为您不必重写Eloquent方法并且会导致相同的行为,但可以更好地控制模型 .

    只需将其添加到您的模型:

    protected static function boot()
    {
        parent::boot();
    
        static::addGlobalScope('exclude_deleted', function (Builder $builder) {
            $builder->whereNull('deleted_at');
        });
    }
    

    您还可以创建子Scope类并将其重用于多个模型 .

    有关更多信息,Laravel doc几乎解释了它的一切:https://laravel.com/docs/5.6/eloquent#global-scopes

相关问题