[英]How do I get all subcategories of parent categories in Laravel?
我在$categories
變量中有所有父類別,在$subCats
變量中有所有子類別。 問題是,除了子類別之外,空的父類別也落入$subCats
變量中。 你怎么能解決這個問題?
public function showForm()
{
$subCats = [];
$categories = Category::where('parent_slug', null)->get();
foreach($categories as $cats) {
$subCats[] = Category::where('parent_slug', $cats->slug)->get();
}
return view('user.form', compact('categories', 'subCats'));
}
嘗試這個:
public function showForm()
{
$subCats = [];
$categories = Category::where('parent_slug', null)->get();
foreach($categories as $cats) {
$subCat = Category::where('parent_slug', $cats->slug)->get();
if($subCat->count()) {
$subCats[] = $subCat;
}
}
return view('user.form', compact('categories', 'subCats'));
}
我認為您不需要循環:
$categories = Category::where('parent_slug', null)->get();
$subCats = Category::where('parent_slug', '!=', null)->get();
return view('user.form', compact('categories', 'subCats'));
為了獲得更高的性能,您可以在集合上使用whereNull()方法進行過濾:
$data = Category::get();
$categories = $data->whereNull('parent_slug')->all();
$subCats = $data->whereNotNull('parent_slug')->all();
return view('user.form', compact('categories', 'subCats'));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.