我需要获得产品的类别,只有类别中存在产品的地方,我才有代码:
$categories = Category::with(['children.products', 'products'])->has('children.products')->orHas('products')->whereNull('parent_id')->whereId($category->id)->paginate(15);
但是whereId
= $category->id
无效。为什么?我得到了其他类别的类别。.但是我只需要获得某些类别,其中id = categoryId
型号类别:
public function children()
{
return $this->hasMany(self::class, 'parent_id');
}
public function parent()
{
return $this->belongsTo(self::class, 'parent_id')->withoutGlobalScope('active');
}
public function products()
{
return $this->hasMany(Product::class);
}
答案 0 :(得分:1)
您应该在封闭的函数中结合使用has和orHas,类似于以下内容:
$query->where(function($query) {
$query->has('children.products');
$query->orHas('products');
});
此外,在上面,我建议使用“ join”,因为“ has”要慢得多。