2016-09-14 109 views
0

概念问题: 我使用touches属性时,自动更新上取决于模型的时间戳有一个非常简单的问题;它正确地这样做,但也适用于全球范围。使用Laravel倒是没有全球范围

有什么方法可以关闭此功能吗?或者专门要求自动touches忽略全局范围?


具体实例: 当配料模型更新所有相关的食谱应该被感动。这工作正常,除了我们有一个globalScope根据区域设置分开配方,这也适用于触摸时使用。


成分型号:

class Ingredient extends Model 
{ 
    protected $touches = ['recipes']; 

    public function recipes() { 
     return $this->belongsToMany(Recipe::class); 
    } 

} 

配方型号:

class Recipe extends Model 
{ 
    protected static function boot() 
    { 
     parent::boot(); 
     static::addGlobalScope(new LocaleScope); 
    } 

    public function ingredients() 
    { 
     return $this->hasMany(Ingredient::class); 
    } 
} 

区域设置范围:

class LocaleScope implements Scope 
{ 
    public function apply(Builder $builder, Model $model) 
    { 
     $locale = app(Locale::class); 

     return $builder->where('locale', '=', $locale->getLocale()); 
    } 

} 

回答

1

如果你想明确地避免全球范围内针对特定查询,你可以使用withoutGlobalScope met HOD。该方法接受全局作用域的类名作为其唯一参数。

$ingredient->withoutGlobalScope(LocaleScope::class)->touch(); 
$ingredient->withoutGlobalScopes()->touch(); 

由于您不直接调用touch(),在您的情况下,它将需要多一点才能使其工作。

您可以在模型$ touches属性中指定应该触及的关系。关系返回查询生成器对象。看看我要去哪里?

protected $touches = ['recipes']; 

public function recipes() { 
    return $this->belongsToMany(Recipe::class)->withoutGlobalScopes(); 
} 

如果您的应用程序的其余打乱,只需要创建一个新的关系,专门为触摸(嘿嘿:)

protected $touches = ['recipesToTouch']; 

public function recipes() { 
    return $this->belongsToMany(Recipe::class); 
} 

public function recipesToTouch() { 
    return $this->recipes()->withoutGlobalScopes(); 
} 
+0

如前所述,我们没有显式调用'触摸()'方法,'touch'会自动通过属性'$ touch.'调用Laravel –

+1

我的不好,请看更新的答案 –