Laravel Eloquent Query Builder Default Where Condition

后端 未结 3 1767
长情又很酷
长情又很酷 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:43

    I normally override newQuery() for this. newQuery() is the method that Eloquent use to construct a new query.

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

    Now your News::all() will only output your news with status = 1.

    0 讨论(0)
  • 2020-12-16 13:45

    It's been already mentioned but here is a quick example using global scope which might be the best current solution since you wont have to override Eloquent methods and would result into the same behavior but with more control of your model.

    Just add this to your model :

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

    You can also create a child Scope class and reuse it for multiple Models.

    For more information, Laravel doc explained pretty much everything about it: https://laravel.com/docs/5.6/eloquent#global-scopes

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题