Nic*_*ank 2 php global-scope laravel
概念问题:
在使用touches属性时,我有一个非常简单的问题,即自动更新依赖模型的时间戳; 它正确地这样做但也适用于全局范围.
有没有办法关闭此功能?或者专门要求自动 touches忽略全局范围?
具体示例:更新配料模型时,应触及所有相关配方.这样可以正常工作,除了我们globalScope根据区域设置分离配方,在应用触摸时也会使用它.
成分模型:
class Ingredient extends Model
{
protected $touches = ['recipes'];
public function recipes() {
return $this->belongsToMany(Recipe::class);
}
}
Run Code Online (Sandbox Code Playgroud)
食谱型号:
class Recipe extends Model
{
protected static function boot()
{
parent::boot();
static::addGlobalScope(new LocaleScope);
}
public function ingredients()
{
return $this->hasMany(Ingredient::class);
}
}
Run Code Online (Sandbox Code Playgroud)
区域范围:
class LocaleScope implements Scope
{
public function apply(Builder $builder, Model $model)
{
$locale = app(Locale::class);
return $builder->where('locale', '=', $locale->getLocale());
}
}
Run Code Online (Sandbox Code Playgroud)
如果要显式避免给定查询的全局范围,可以使用该withoutGlobalScope()方法.该方法接受全局范围的类名作为其唯一参数.
$ingredient->withoutGlobalScope(LocaleScope::class)->touch();
$ingredient->withoutGlobalScopes()->touch();
Run Code Online (Sandbox Code Playgroud)
既然你没有touch()直接打电话,在你的情况下,它需要更多才能使它工作.
您可以指定应在模型$touches属性中触及的关系.关系返回查询构建器对象.看看我要去哪里?
protected $touches = ['recipes'];
public function recipes() {
return $this->belongsToMany(Recipe::class)->withoutGlobalScopes();
}
Run Code Online (Sandbox Code Playgroud)
如果这与你的应用程序的其余部分混淆,只需创建一个专门用于触摸的新关系(呵呵:)
protected $touches = ['recipesToTouch'];
public function recipes() {
return $this->belongsToMany(Recipe::class);
}
public function recipesToTouch() {
return $this->recipes()->withoutGlobalScopes();
}
Run Code Online (Sandbox Code Playgroud)