greetings!
so, i want to get X random models from a parent:
i have sub-categories and they have many products:
i can do SubCategory::with('products')->get()
and i will have a collection of subcats and their products.
however i want to get only a certain number of products per subcategory, after reading some documentation i came up with this:
$var = SubCategory::with(['products' => function($query){
// $query(get X random products...); <- this is what i want
}])->get();
// like so:
$var = SubCategory::with(['products' => function($query){
$query->random()->take(3);
}])->get();
// random() is just a scope.
which works except it only gets ONLY X products in the total, not per subcategory:
i want:
after struggling with this problem i did this solution:
$subCats = SubCategory::all();
$productsCollection = collect();
foreach ($subCats as $cat) {
$productsCollection->push($cat->products()->random()->take(3)->get());
}
that works as i want to, however i'm pretty sure there's a better and elegant solution.
any help/advice is much appreciated, thanks for reading!
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community