Я создал ресурс 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,
}
}
]
Функция groupBy:
$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');
});
Заранее спасибо за помощь.