类别和课程是两个表。基于类别,可以将“n”个数据插入到课程中。获取 API 响应时,应该如下所示。
控制器
public function catlist($catid)
{
$category =
DB::table('courses')
->join('categories', 'courses.category_id', '=', 'categories.id')// joining the Categories table , where category_id and categories id are same
->select(
'categories.id as catid',
'categories.name as catname',
'courses.id as courseid',
'courses.title as coursename'
)
->where('courses.category_id', '=', $catid)
->get();
foreach ($category as $cat)
{
$data = [
'category'=>[
"id" => $cat->catid,
"name" => $cat->catname,
],
'courselist'=>[
"id" => $cat->courseid,
"name" => $cat->coursename,
]
];
}
return response()->json([
'success' => true,
'data' => $data,
],200);
}
实际结果是:
"data": {
"category": {
"id": 1,
"name": "Test Category"
},
"courseList": {
"id": 2,
"title": "Course 2"
}
}
预期结果将是:
data=[
category: {
id: 1,
name: "Test Category"
},
courseList: [
{
id: 1,
title: "Course 1",
},
{
id: 2,
title: "Course 2",
},
],
]
您的查询为每个课程和类别返回一行,您应该使用正常的 Laravel 关系,或者您需要在查询中使用 sql groupBycategories.id 方法。