我在Laravel有一个使用软删除的模型帐户。除此之外,我还想要另一个名为active的专栏,它的行为也是一样的。如果它的设置为XXX,那么所有的Account::
调用都不应该包含在返回中。在我将活动值设置为YYY之前,在此之后,应该包括它们。有办法这样做吗?我想设置自己的XXX和YYY值。因此,我可以说,只有当活动=1或active = whatEverIWant时才返回
编辑:我知道我可以在每个电话中检查这个值,但是我已经在很多地方使用了这个帐户,所以我不想在任何地方添加它。
发布于 2020-12-17 05:20:21
可以用两种方式来处理
选项1:全局范围
您可以在模型上定义一个全局范围,它只返回活动设置为1的记录。
class Account extends Model
{
protected static function booted()
{
static::addGlobalScope('active', function (Builder $builder) {
$builder->where('active', 1);
});
}
// rest of the class code
}
现在,模型上的所有查询都将在全局范围内定义约束。
当您确实希望检索记录时,无论active是否设置为1 not,您都可以使用withoutGlobalScopes()
或withoutGlobalScope('active')
调用它--将删除全局范围中定义的约束。
$accounts = Account::withoutGlobalScopes()->get();
//OR
$accounts = Account::withoutGlobalScope('active');
选项2:本地作用域
可以在模型类上为每个活动状态和非活动状态定义一个本地范围。
class Account extends Model
{
public function scopeActive($query)
{
$query->where('active', 1);
}
public function scopeInactive($query)
{
$query->where('active', '<>', 1);
}
}
然后,当您想要筛选活动或非活动的记录时。
$activeAccounts = Account::active()->get();
$inactiveAccounts = Account::inactive()->get();
$accounts = Account::get(); //to get all records irrespective of whether active or inactive
Laravel软删除也在幕后使用范围。
Laravel博士:https://laravel.com/docs/master/eloquent#query-scopes
https://stackoverflow.com/questions/65341102
复制