如何为模型中的所有 select 查询定义默认 where 条件?
How can I define default where condition for all select queries in my models?
我需要在我的模型中设置一个默认的 where 条件。
所以实际上我必须在所有 select 查询中设置它。
查询如:
->where('status','active')
你应该试试这个:
您的模特:
class News extends Eloquent {
public function scopeStatus($query)
{
return $query->where('status', '=', 1);
}
}
您的控制器:
$news = News::status()->get();
您可以在模型中使用 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();
您可以使用全局范围:
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');
});
}
我需要在我的模型中设置一个默认的 where 条件。
所以实际上我必须在所有 select 查询中设置它。
查询如:
->where('status','active')
你应该试试这个:
您的模特:
class News extends Eloquent {
public function scopeStatus($query)
{
return $query->where('status', '=', 1);
}
}
您的控制器:
$news = News::status()->get();
您可以在模型中使用 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();
您可以使用全局范围: 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');
});
}