Laravel Eloquent Query Builder Default Where Condition

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

提交回复
热议问题