In Laravel 5.4, I have my relationship:
public function products()
{
return $this->hasMany(Product::class);
}
public function category()
{
return $this->belongsTo(Category::class);
}
And my query is:
$x = Category::with('products')->where('active', 1)->get();
It does show all category names correctly, but how to count only product 'active = 1'? I don't wish to count all products, but active products only.
try this:
$x = Category::with(['products' => function($query) { $query->where('active','=', 1); }])->where('active', 1)->get();
That will give you products that are active and then only categories where products are active.