全局查询范围和与Laravel 5的关系

时间:2015-05-05 14:09:56

标签: php laravel eloquent laravel-5

我试图熟悉雄辩并且我一直在玩一些全球查询范围,但是当谈到它对关系的影响时,我没有取得多大成功

我有两个型号;产品和类别,每个都添加了一些全局查询范围。

产品:

use productConditions;

protected $table = 'product';
public $timestamps = false;

private $websiteDetails;

public function __construct(){
    parent::__construct();
    $this->websiteDetails = session('website');
}

public function scopeByCategory($query, $categoryId){
    return $query->whereHas('categories', function($q) use ($categoryId){
        $q->where('id', $categoryId);
    });
}

public function categories(){
    return $this->belongsToMany('App\Category', 'product_category', 'product_id', 'category_id');
}

类别:

use categoryConditions;

protected $table = 'category';
public $timestamps = false;

public function products() {
    return $this->belongsToMany('App\Product', 'product_category', 'category_id', 'product_id');
}

我使用traits来引导全局范围,文件如下:

所以对于产品:

public function apply(Builder $builder, Model $model)
{
    $builder->where('state', 'a');
    $builder->where('stock_level', '>', 0);
}

public function remove(Builder $builder, Model $model){

    $query = $builder->getQuery();

    foreach((array) $query->wheres as $key => $where){

        if($where['column'] == 'state'){
            unset($query->wheres[$key]);
        }

        if($where['column'] == 'stock_level'){
            unset($query->wheres[$key]);
        }

    }
    $query->wheres = array_values($query->wheres);
}

和类别

public function apply(Builder $builder, Model $model)
{
    $websiteDetails = session('website');
    $builder->where('website_id', $websiteDetails['id']);
}

public function remove(Builder $builder, Model $model){

    $query = $builder->getQuery();

    foreach((array) $query->wheres as $key => $where){

        if($where['column'] == 'website_id'){
            unset($query->wheres[$key]);
        }
    }
    $query->wheres = array_values($query->wheres);
}

因为具有特定ID的类别字段有多个记录,因为面部有多个网站配置文件。我想为类别设置全局查询范围 - > website_id。

所以当做这样的事情时,这很有效:

$category = Category::with('products')->first();
$category->products;

它获取具有指定website_id的所有类别,然后提取产品。

然而,当我在模型中设置查询范围时,它做的工作本质上是相同的,但反之亦然。所以,这不起作用:

$category = Product::byCategory(2)->get();

除非,我删除了类别模型中的全局查询范围,并将whereHas闭包修改为:

public function scopeByCategory($query, $categoryId){
    return $query->whereHas('categories', function($q) use ($categoryId){
        $q->where('id', $categoryId)->where('website_id', $this->websiteDetails['id']);
    });
}

但这样做意味着我无法再查询Category模型,而无需设置某种类型的byWebsite查询范围方法。

有人可以告诉我,我是不是以某种方式做错了,或者建议我解决问题。

非常感谢

1 个答案:

答案 0 :(得分:0)

尝试覆盖类别模型中的查询方法,它应该适用于类别。

public function newQuery($excludeDeleted = true) { $websiteDetails = session('website'); return parent::newQuery()->where('website_id', $websiteDetails['id']); }

如果它不能用作产品关系,请试试这个:

public function categories(){ return $this->belongsToMany('App\Category', 'product_category', 'product_id', 'category_id') ->where('website_id', $this->websiteDetails['id']); }); }