2016-09-14 108 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

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