I am using Laravel 5.6 and MySQL. I have categories, sub-categories, category_info, and services.
A category can have 1 or more sub-categories. A category belongs to one menu category
A sub-category has only one category.
A category has 1 category info record. It doesn't matter if its a category or subcategory it will have one record in the category_info table.
My table structure is as follows
Menu_Categories
id
1,
2
Categories
id, parent_category_id, menu_category_id
1, null, 1
2, null, 1
3, 1, null
4, 1, null
Category_Info
category_id, name
1, Legal Services
2, Misc
3, US Legal Services
4, Europe Legal Services
Controller
$cats = MenuCategories
::with(['categories', 'categories.info', 'categories.sub_categories'])
->get();
Menu Categories Model
public function categories() {
return $this->hasMany(Categories::class, 'menu_category_id', 'id');
}
Categories Model
public function menu_categories() {
return $this->belongsTo(MenuCategories::class, 'menu_category_id');
}
public function sub_categories() {
return $this->hasOne(Categories::class, 'parent_category_id');
}
public function info() {
return $this->hasOne(CategoryInfo::class, 'category_id');
}
SubCategory Info Model
public function category() {
return $this->belongsTo(CategoryInfo::class);
}
I need to return the categories and the category info as follows
{
Categories: {
{
id: 1,
parent_category_id, null,
Sub_Categories: {
{
id: 3
parent_category_id: 1
Category_Info: {
{
category_id: 3,
name: US Legal Services
}
}
},
{
id: 4
parent_category_id: 1,
Category_Info: {
{
category_id: 4,
name: Europe Legal Services
}
}
},
},
Category_Info: {
{
category_id: 3,
name: Legal Services
}
}
},
{
id: 2,
parent_category_id, null,
Category_Info: {
{
category_id: 3,
name: Misc
}
}
},
}
}
With the way I have relationships set up it is returning data incorrectly. It is not returning Category_Info for sub-categories.
{
Categories: {
{
id: 1,
parent_category_id, null,
Sub_Categories: {
{
id: 3
parent_category_id: 1
},
{
id: 4
parent_category_id: 1,
},
},
Category_Info: {
{
category_id: 3,
name: Legal Services
}
}
},
{
id: 2,
parent_category_id, null,
Category_Info: {
{
category_id: 3,
name: Misc
}
}
},
}
}
Is it possible to return Category_Info for the sub-categories as well? Thanks in advance
from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2GLcZ7d
via
IFTTT