Laravel Global Scope不适用于嵌套的where


Laravel Global Scope not working with nested where

我正试图使用一个由特征加载到特定模型上的作用域,以便它在该模型的每个查询中都这样做

但是

查询不起作用

public function apply(Builder $builder) {
    $builder->where(function($q){$q->whereIn('region_id', array(1,2))
            ->orWhere('manager_id', 1);
    });
}

这是它应该做的,但页面没有加载,所以我检查了apache错误日志,得到了一个:

[core:notice] [pid 949] AH00051: child pid 2647 exit signal Segmentation fault (11), possible coredump in /etc/apache2

但是如果我只对一个查询应用相同的creteria,那么它就起作用了:S

Client::where(function($q){
        $q->whereIn('region_id', array(1,2))
          ->orWhere('manager_id', 1);
})->get();

那么这里出了什么问题?看起来构建器不喜欢接受函数,因为我在函数中放入什么并不重要,它只是不起作用

适合您的解决方案-使用whereNested:

public function apply(Builder $builder) {
    $builder->whereNested(function ($q) {
          $q->whereIn('region_id', array(1,2))
            ->orWhere('manager_id', 1);
    });
}

说明:

$builder->where 

Eloquent'Builder方法,导致无限循环,因为它正在调用没有作用域的新查询,它调用新查询,首先引导作用域。。。

While:

$builder->whereNested

在调用Query'Builder方法的情况下,它按预期工作。由于Eloquent'Builder上缺少whereNested方法和神奇的__call方法,函数调用被转发到Query'Builder对象。

我不是这方面的专家,但在第一个解决方案中,您没有定义$q,所以我认为它不起作用。你可以试试:

public function apply(Builder $builder) {
    $builder->whereIn('region_id', array(1,2))->orWhere('manager_id', 1);
}

public function apply(Builder $builder) {
    $builder->where(function() use $builder {$builder->whereIn('region_id', array(1,2))
            ->orWhere('manager_id', 1);
    });
}