概念问题:
我在使用 touches 属性时遇到了一个非常简单的问题,即自动更新依赖模型的时间戳;它正确地这样做,但也适用于全局范围。

有什么办法可以关闭这个功能吗?或者专门要求 自动 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());
    }

}

最佳答案

如果你想明确地避免给定查询的全局范围,你可以使用 withoutGlobalScope() 方法。该方法接受全局范围的类名作为其唯一参数。

$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();
}

关于php - 在没有全局作用域的情况下使用 Laravel touches,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39490959/

10-11 12:40
查看更多