在没有全局作用域的情况下使用 Laravel touches
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39490959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use Laravel touches without global scopes
提问by Nicklas Kevin Frank
Concept Problem:I have a very simple problem when using the touches
attribute, to automatically update timestamp on a depending model; it correctly does so but also applies the global scopes.
概念问题:我在使用touches
属性时遇到一个非常简单的问题,即在依赖模型上自动更新时间戳;它正确地这样做,但也适用于全局范围。
Is there any way to turn this functionality off? Or to ask specifically for automatictouches
to ignore global scopes?
有什么办法可以关闭这个功能吗?或者专门要求自动touches
忽略全局范围?
Concrete Example:
When an ingredient model is updated all related recipes should be touched. This works fine, except we have a globalScope
for separating the recipes based on locales, that also gets used when applying the touches.
具体示例:当更新成分模型时,应触及所有相关配方。这很好用,除了我们有一个globalScope
用于根据语言环境分离食谱的方法,在应用触摸时也会使用它。
Ingredient Model:
配料型号:
class Ingredient extends Model
{
protected $touches = ['recipes'];
public function recipes() {
return $this->belongsToMany(Recipe::class);
}
}
Recipe Model:
配方型号:
class Recipe extends Model
{
protected static function boot()
{
parent::boot();
static::addGlobalScope(new LocaleScope);
}
public function ingredients()
{
return $this->hasMany(Ingredient::class);
}
}
Locale Scope:
区域范围:
class LocaleScope implements Scope
{
public function apply(Builder $builder, Model $model)
{
$locale = app(Locale::class);
return $builder->where('locale', '=', $locale->getLocale());
}
}
回答by Tadas Paplauskas
If you want to explicitly avoid a global scope for a given query, you may use the withoutGlobalScope()
method. The method accepts the class name of the global scope as its only argument.
如果您想显式避免给定查询的全局范围,您可以使用该withoutGlobalScope()
方法。该方法接受全局范围的类名作为其唯一参数。
$ingredient->withoutGlobalScope(LocaleScope::class)->touch();
$ingredient->withoutGlobalScopes()->touch();
Since you're not calling touch()
directly, in your case it will require a bit more to make it work.
由于您不是touch()
直接调用,因此在您的情况下,需要更多时间才能使其工作。
You specify relationships that should be touched in model $touches
attribute. Relationships return query builder objects. See where I'm going?
您指定应该在模型$touches
属性中触及的关系。关系返回查询构建器对象。看到我要去哪里了吗?
protected $touches = ['recipes'];
public function recipes() {
return $this->belongsToMany(Recipe::class)->withoutGlobalScopes();
}
If that messes with the rest of your application, just create a new relationship specifically for touching (heh :)
如果这与您的应用程序的其余部分混淆,只需创建一个专门用于触摸的新关系(呵呵:)
protected $touches = ['recipesToTouch'];
public function recipes() {
return $this->belongsToMany(Recipe::class);
}
public function recipesToTouch() {
return $this->recipes()->withoutGlobalScopes();
}