Reputation: 294
I want to filter only those categories which have at least one product. I write Category::with('products')->… but how do I filter out those empty categories? Those with no product?
app\Category.php:
class Category extends Model {
// ...
public function products() {
return $this->hasMany('App\Product');
}
// ...
}
app\Http\Controller\CategoriesController.php:
function getIndex() {
$categories = Category::with('products')->get();
return view('categories.index', compact('categories'));
}
Upvotes: 0
Views: 495
Reputation:
Us the has
function
Category::with('products')->has('products')->get()
Upvotes: 1
Reputation: 294
I have found solution..
There’s an app function for that: has().
app\Http\Controller\CategoriesController.php:
function getIndex() {
$categories = Category::with('products')->has('products')->get();
return view('categories.index', compact('categories'));
}
Upvotes: 0
Reputation: 15306
You can use has
in it
$users = Category::has('products')->get();
// only Categories that have at least one product are contained in the collection
has()
is to filter the selecting model based on a relationship. So it acts very similarly to a normal WHERE condition. If you just use has('relation')
that means you only want to get the models that have at least one related model in this relation.
Upvotes: 2