如何为模型中的所有select查询定义默认where条件?

juzqafwq  于 2021-06-17  发布在  Mysql
关注(0)|答案(3)|浏览(338)

我需要在我的模型中设置一个默认的where条件。
所以实际上我必须在all select查询中设置它。
查询方式:

->where('status','active')
yh2wf1be

yh2wf1be1#

您可以在模型中使用laravel范围(本地范围或全局范围):
全局范围示例:
在model.php中:

protected static function boot()
    {
        parent::boot();    
        static::addGlobalScope('status', function (Builder $builder) {
            $builder->where('status', 'active');
        });
    }

本地范围示例:
在model.php中

public function scopeIsActive($query)
    {
        return $query->where('status', 'active');
    }

在控制器中:

Model::isActive()->get();

来源

zrfyljdw

zrfyljdw2#

你应该试试这个:
您的型号:

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

您的控制器:

$news  = News::status()->get();
dzjeubhm

dzjeubhm3#

您可以使用全局范围:https://laravel.com/docs/5.7/eloquent#global-范围
把它写在你想要查询的模型中

/**
 * The "booting" method of the model.
 *
 * @return void
 */
protected static function boot()
{
    parent::boot();

    static::addGlobalScope('status', function (Builder $builder) {
        $builder->where('status', 'active');
    });
}

相关问题