我正在努力熟悉雄辩,我一直在玩一些全局查询范围,但是当谈到它对关系的影响时,我没有取得多大成功 .
我有两个型号;产品和类别,每个都添加了一些全局查询范围 .
产品介绍:
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');
}
我正在使用特征来引导全局范围,文件如下:
所以对于产品:
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 回答
尝试覆盖类别模型中的查询方法,它应该适用于类别 .
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']); }); }