我创建了一个 API 资源,它使用 groupBy 方法返回特定导师的选定主题和类别,
问题是,groupBy 方法没有像我预期的那样发送响应。
请在下面找到当前和预期的响应,
当前 API 响应
"Web Design": [
{
"id": 542,
"name": "WordPress",
"category_name": "Web Design",
"pivot": {
"tutor_id": 4,
"subject_id": 542,
"subject_category_id": 70,
}
},
{
"id": 542,
"name": "WordPress",
"category_name": "Web Design",
"pivot": {
"tutor_id": 4,
"subject_id": 542,
"subject_category_id": 70,
}
}
],
"Graphic Design": [
{
"id": 547,
"name": "Photoshop",
"category_name": "Graphic Design",
"pivot": {
"tutor_id": 4,
"subject_id": 542,
"subject_category_id": 71,
}
},
{
"id": 548,
"name": "WordPress",
"category_name": "Graphic Design",
"pivot": {
"tutor_id": 4,
"subject_id": 542,
"subject_category_id": 71,
}
}
]
分组功能:
$subjects = $this->tutor->subjects->map(function($subject){
$subject->category_name = SubjectCategory::find($subject->pivot->subject_category_id)->name;
return $subject;
});
$subjectData = $subjects->groupBy('category_name');
预期的 API 响应
"category": "Web Design",
"subjects": [
{
"id": 542,
"name": "WordPress",
"category_name": "Web Design",
"pivot": {
"tutor_id": 4,
"subject_id": 542,
"subject_category_id": 70,
}
},
{
"id": 542,
"name": "WordPress",
"category_name": "Web Design",
"pivot": {
"tutor_id": 4,
"subject_id": 542,
"subject_category_id": 70,
}
}
],
"category": "Graphic Design",
"subjects": [
{
"id": 547,
"name": "Photoshop",
"category_name": "Graphic Design",
"pivot": {
"tutor_id": 4,
"subject_id": 542,
"subject_category_id": 71,
}
},
{
"id": 548,
"name": "WordPress",
"category_name": "Graphic Design",
"pivot": {
"tutor_id": 4,
"subject_id": 542,
"subject_category_id": 71,
}
}
]
请查找主题类别、主题和主题类别表的给定迁移。
迁移:主题类别
Schema::create('subject_categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('slug');
$table->integer('parent_id')->nullable();
$table->unsignedTinyInteger('is_deleted')->default(SubjectCategory::IS_DELETED);
$table->timestamps();
});
迁移:CreateSubjectsTable
Schema::create('subjects', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('slug');
$table->integer('isActive');
$table->timestamps();
});
迁移:CreateSubjectSubjectCategoryTable
Schema::create('subject_subject_category', function (Blueprint $table) {
$table->increments('id');
$table->integer('subject_id')->unsigned();
$table->integer('subject_category_id')->unsigned();
});
Schema::table('subject_subject_category', function($table) {
$table->foreign('subject_id')->references('id')->on('subjects');
$table->foreign('subject_category_id')->references('id')->on('subject_categories');
});
提前感谢您的帮助。