douyi6168 2016-09-14 12:53
浏览 39
已采纳

在没有全局范围的情况下使用Laravel触摸

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.

Is there any way to turn this functionality off? Or to ask specifically for automatic touches to ignore global scopes?


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.


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

}
  • 写回答

1条回答 默认 最新

  • dongyao2022 2016-09-14 13:18
    关注

    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.

    $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.

    You specify relationships that should be touched in model $touches attribute. Relationships return query builder objects. See where I'm going?

    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();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效