【发布时间】:2019-05-25 06:38:18
【问题描述】:
我需要在我的模型中设置默认 where 条件。
所以实际上我必须在我的所有选择查询中设置它。
查询如下:
->where('status','active')
【问题讨论】:
标签: mysql laravel model eloquent default
我需要在我的模型中设置默认 where 条件。
所以实际上我必须在我的所有选择查询中设置它。
查询如下:
->where('status','active')
【问题讨论】:
标签: mysql laravel model eloquent default
您可以使用全局范围: https://laravel.com/docs/5.7/eloquent#global-scopes
将其写入您要使用条件查询的模型中
/**
* The "booting" method of the model.
*
* @return void
*/
protected static function boot()
{
parent::boot();
static::addGlobalScope('status', function (Builder $builder) {
$builder->where('status', 'active');
});
}
【讨论】:
你可以在模型中使用 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();
【讨论】:
你应该试试这个:
你的模特:
class News extends Eloquent {
public function scopeStatus($query)
{
return $query->where('status', '=', 1);
}
}
你的控制器:
$news = News::status()->get();
【讨论】: