Поскольку вы новичок в Laravel, вы можете не знать, что такое Eloquent.
И если я правильно понимаю ваш вопрос, у нас есть 3 таблицы, и нам нужно связать их через отношения, чтобы мы могли получить каждый элемент реляционного объекта с данными.
Итак, у нас есть 3 таблицы:
- category_types
- main_categories
- sub_categories
Примечание: допускается, что названия таблиц во множественном числе, а названия моделей в единственном числе. Например: category_types для таблицы и CategoryType для класса модели.
Хорошо, прежде всего, вам нужно создать миграции:
php artisan make:migration create_category_types_table
public function up()
{
Schema::create('category_types', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name', 255)->nullable();
$table->timestamps();
});
}
php artisan make:migration create_main_categories_table
public function up()
{
Schema::create('main_categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('category_type_id')->index();
$table->string('name', 255)->nullable();
$table->timestamps();
});
}
php artisan make:migration create_sub_categories_table
public function up()
{
Schema::create('sub_categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('category_type_id')->index();
$table->bigInteger('main_category_id')->index();
$table->string('name', 255)->nullable();
$table->timestamps();
});
}
Итак, в функции этой миграции у нас есть автоинкремент и имя
Обратите внимание, что вы можете написать только имя в этой таблице, а не category_name и category_type_id как
Вы всегда знаете, что этот атрибут относится к таблице партуклара
Хорошо, теперь мы можем создавать и настраивать наши модели. Для модели CategoryTypes мы должны
создайте 2 отношения для main_categories и sub_categories, например:
php artisan make:model CategoryType
php artisan make:model MainCategory
php artisan make:model SubCategory
И это код модели нашей категории:
class CategoryType extends Model {
protected $fillable = ['name'];
protected $dates = [
'created_at',
'updated_at'
];
public function mainCategories()
{
return $this->hasMany(MainCategory::class);
}
public function subCategories() {
return $this->hasMany(SubCategory::class);
}
}
Поскольку мы определяем наши реализации модели CategoryType, мы можем теперь получать данные, которые нам нужны в нашем контроллере:
public function fetchCategory()
{
$categories = CategoryType::with(['mainCategories', 'subCategories'])->get();
return response()->json($categories, 200);
}
И наш JSON:
[
{
"id": 1,
"name": "Books",
"created_at": "2019-05-19 13:24:51",
"updated_at": "2019-05-19 13:24:51",
"main_categories": [
{
"id": 1,
"category_type_id": 1,
"name": "Si-Fi",
"created_at": "2019-05-19 13:26:07",
"updated_at": "2019-05-19 13:26:08"
},
{
"id": 2,
"category_type_id": 1,
"name": "Biography ",
"created_at": "2019-05-19 13:26:33",
"updated_at": "2019-05-19 13:26:34"
},
{
"id": 3,
"category_type_id": 1,
"name": "Tall tale ",
"created_at": "2019-05-19 13:26:57",
"updated_at": "2019-05-19 13:26:58"
},
{
"id": 4,
"category_type_id": 1,
"name": "Short story",
"created_at": "2019-05-19 13:27:07",
"updated_at": "2019-05-19 13:27:07"
},
{
"id": 5,
"category_type_id": 1,
"name": "Fantasy",
"created_at": "2019-05-19 13:27:17",
"updated_at": "2019-05-19 13:27:18"
}
],
"sub_categories": [
{
"id": 1,
"category_type_id": 1,
"main_category_id": 1,
"name": "Space exploration",
"created_at": "2019-05-19 13:42:35",
"updated_at": "2019-05-19 13:42:35"
},
{
"id": 2,
"category_type_id": 1,
"main_category_id": 2,
"name": "Historical biography",
"created_at": "2019-05-19 13:42:36",
"updated_at": "2019-05-19 13:42:36"
},
{
"id": 3,
"category_type_id": 1,
"main_category_id": 5,
"name": "The Lord of the Rings",
"created_at": "2019-05-19 13:42:37",
"updated_at": "2019-05-19 13:42:37"
}
]
},
{
"id": 2,
"name": "Sports",
"created_at": "2019-05-19 13:24:57",
"updated_at": "2019-05-19 13:24:57",
"main_categories": [
{
"id": 6,
"category_type_id": 2,
"name": "Popular Sports",
"created_at": "2019-05-19 13:27:35",
"updated_at": "2019-05-19 13:27:36"
},
{
"id": 7,
"category_type_id": 2,
"name": "Team Sports",
"created_at": "2019-05-19 13:27:35",
"updated_at": "2019-05-19 13:27:36"
},
{
"id": 8,
"category_type_id": 2,
"name": "Racquet Sports",
"created_at": "2019-05-19 13:27:35",
"updated_at": "2019-05-19 13:27:36"
},
{
"id": 9,
"category_type_id": 2,
"name": "Fitness",
"created_at": "2019-05-19 13:27:35",
"updated_at": "2019-05-19 13:27:36"
},
{
"id": 10,
"category_type_id": 2,
"name": "Recreation",
"created_at": "2019-05-19 13:27:35",
"updated_at": "2019-05-19 13:27:36"
}
],
"sub_categories": [
{
"id": 4,
"category_type_id": 2,
"main_category_id": 6,
"name": "Football",
"created_at": "2019-05-19 13:42:37",
"updated_at": "2019-05-19 13:42:37"
},
{
"id": 5,
"category_type_id": 2,
"main_category_id": 6,
"name": "Basketball",
"created_at": "2019-05-19 13:42:37",
"updated_at": "2019-05-19 13:42:37"
}
]
},
{
"id": 3,
"name": "Study",
"created_at": "2019-05-19 13:25:24",
"updated_at": "2019-05-19 13:25:25",
"main_categories": [
{
"id": 11,
"category_type_id": 3,
"name": "Web Development",
"created_at": "2019-05-19 13:27:35",
"updated_at": "2019-05-19 13:27:36"
},
{
"id": 12,
"category_type_id": 3,
"name": "Sofware Development",
"created_at": "2019-05-19 13:27:35",
"updated_at": "2019-05-19 13:27:36"
},
{
"id": 13,
"category_type_id": 3,
"name": "Mangement",
"created_at": "2019-05-19 13:27:35",
"updated_at": "2019-05-19 13:27:36"
},
{
"id": 14,
"category_type_id": 3,
"name": "Tourism",
"created_at": "2019-05-19 13:27:35",
"updated_at": "2019-05-19 13:27:36"
},
{
"id": 16,
"category_type_id": 3,
"name": "Geography",
"created_at": "2019-05-19 13:33:36",
"updated_at": "2019-05-19 13:33:37"
}
],
"sub_categories": [
{
"id": 6,
"category_type_id": 3,
"main_category_id": 11,
"name": "PHP",
"created_at": "2019-05-19 13:42:29",
"updated_at": "2019-05-19 13:42:30"
},
{
"id": 7,
"category_type_id": 3,
"main_category_id": 11,
"name": "Ruby",
"created_at": "2019-05-19 13:42:31",
"updated_at": "2019-05-19 13:42:32"
},
{
"id": 8,
"category_type_id": 3,
"main_category_id": 11,
"name": "Java",
"created_at": "2019-05-19 13:42:33",
"updated_at": "2019-05-19 13:42:33"
}
]
}
]
Надеюсь, это поможет вам. И, пожалуйста, прочитайте Laravel Docs для получения дополнительной информации