Laravel Eloquent Query Builder Default Where Condition

后端 未结 3 1774
长情又很酷
长情又很酷 2020-12-16 13:05

I have News model, when i query news, i want it brings news where status = 1 as default.

News::all(); // select * from news where status = 1
News::where(\'an         


        
3条回答
  •  长情又很酷
    2020-12-16 13:49

    I think the closes you'll get, without actually going in to change some core files...

    is Query Scope...

    Scopes allow you to easily re-use query logic in your models. To define a scope, simply prefix a model method with scope:

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

    Utilizing that scope

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

    Its not quite what you wanted...but its definitely a little shorter than typing

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

    over and over

提交回复
热议问题