Laravel 5:仅按活动产品计算产品类别

时间:2017-05-31 02:45:32

标签: laravel count

在Laravel 5.4中,我有我的关系:

public function products()
{
    return $this->hasMany(Product::class);
}

public function category()
{
    return $this->belongsTo(Category::class);
}

我的疑问是:

$x = Category::with('products')->where('active', 1)->get();

它确实正确显示所有类别名称,但如何只计算产品' active = 1'?我不想计算所有产品,只计算有效产品。

4 个答案:

答案 0 :(得分:1)

试试这个:

$x = Category::with(['products' => function($query) { $query->where('active','=', 1); }])->where('active', 1)->get();

这将为您提供有效的产品,然后只提供产品有效的类别。

答案 1 :(得分:1)

尝试更具体一点。另外还有@linuxartisan的想法

$x = Category::whereHas('products', function ($query) {
         $query->where('products.active', '=', 1);
     })
     ->where('categories.active', '=', 1)
     ->get();

答案 2 :(得分:0)

我假设你有产品.rule1字段以及类别

试试这个查询

active

答案 3 :(得分:0)

public function products()
{
    return $this->hasMany(Product::class)->where('active',1);
}

这在Laravel 7中有效

相关问题