这是代码
public function getSubCategory(Request $request)
{
$response = array();
try {
$categories = Category::where(['status' => 0, 'parent_id' => 0])- >get();
$subCategory = Category::where('status', 0)->where('parent_id', '!=', 0)->get();
foreach ($subCategory as $sub) {
$categoryTitle = Category::where(['id' => $sub->parent_id])- >get(['title']);
$result[] = array(
'cat_title' => $categoryTitle[0]->title,
'sub_title' => $sub->title,
);
}
if (count($result) > 0) {
$response = (new ApiMessageController())->successResponse($result, "Categories List Found!");
} else {
$response = (new ApiMessageController())->failedresponse("No Categories List Found");
}
} catch (\Illuminate\Database\QueryException $ex) {
$response = (new ApiMessageController())->queryexception($ex);
}
return $response;
}
我想显示父类别及其下的子类别。像这样:
- 类别
- Sub 1
- Sub 2
- 类别
- Sub 1
- Sub 2
我想显示类似see demo
的数据数据库结构。 类别和子类别都在同一表中。 Database
答案 0 :(得分:1)
我建议您使用NestedSet
。因此,您可以创建类别树并按深度获取所有数据。
但是在使用它之前,您需要了解
您可以看到所有的here详细信息
答案 1 :(得分:0)
试试这个::
this
输出:
public function getSubCategory(Request $request)
{
$response = array();
try {
$allData = array();
// get all parent category
$categories = Category::where(['status' => 0, 'parent_id' => 0])->get();
foreach ($categories as $key=>$sub) {
// now take one by one it's child category
$subCategory = Category::where('status', 0)->where('parent_id', '=', $sub->id)->get();
$subCat = array();
// set parent category title
$allData[$key]['parent'] = $sub->title;
foreach ($subCategory as $k=>$subcat) {
$subCat[$subcat->id] = $subcat->title
}
// set child category array
$allData[$key]['child'] = $subCat;
}
if (count($allData) > 0) {
$response = (new ApiMessageController())->successResponse($allData, "Categories List Found!");
} else {
$response = (new ApiMessageController())->failedresponse("No Categories List Found");
}
} catch (\Illuminate\Database\QueryException $ex) {
$response = (new ApiMessageController())->queryexception($ex);
}
return $response;
}
也许这会对您有所帮助。
答案 2 :(得分:0)
这就是我将继续的方式:
这是我的代码的样子:
public function getSubCategory(Request $request){
$response = array();
try {
$categories = Category::where(['status' => 0, 'parent_id' => 0])- >get();
foreach ($categories as $c) {
$subcategories = Category::where("parent_id", $c->id)->get();
$response[] = [$c, $subcategories];
}
if (count($response) > 0) {
$response = (new ApiMessageController())->successResponse($result, "Categories List Found!");
} else {
$response = (new ApiMessageController())->failedresponse("No Categories List Found");
}
} catch (\Illuminate\Database\QueryException $ex) {
$response = (new ApiMessageController())->queryexception($ex);
}
return $response;
}
希望我的助手帮忙!