Laravel返回类别(如果存在产品)

时间:2018-12-08 09:06:10

标签: php laravel

我有此代码:

$categories = Category::with('products')->where('parent_id', null)->paginate(15);

如何返回存在产品的变量categories类别?

我认为需要在哪里使用

    $categories = Category::with('products')->where('parent_id', null)->whereHas('products', function($prods) { return ! $prods->isEmpty() })->paginate(15);

请帮助解决它。

型号类别:

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

2 个答案:

答案 0 :(得分:1)

您可以按照document(查询关系存在)使用has函数

$categories = Category::with('products')->has('products')->where('parent_id', null)->paginate(15);

答案 1 :(得分:0)

您可以使用has函数获取记录,例如:

$categories = Category::has('products')
                       ->whereNull('parent_id')
                       ->paginate(15);