I want to display the values of columns with the same menu_id
and the same menu_parentid
. However, the array is empty when I execute in Postman. I want the values of columns with common menu_id
and menu_parentid
displayed in an array.
Controller
public function showMenu()
{
return [
'menus' => Menu::whereColumn('menu_parentid', 'menu_id')
->distinct()
->get()
->map(function ($item) {
return [
'menu_id' => $item->menu_id,
'menu_name' => $item->menu_name,
'menu_icon' => $item->menu_icon,
];
})
];
}
When I test on Postman, I get the following
{
"menus": []
}
CodePudding user response:
I think you're going about this the wrong way. Instead of doing a query like that, you can make a relationship of the model with itself to get the $menu->children
and then perform the array mapping the way you like. I don't want to write it out and guess how you like it to be displayed, so can you elaborate how you would like the array to be structured? Is it like this?:
"menus": [
[parent_id1, child_id1],
[parent_id1, child_id2],
[parent_id2, child_id3]
];
Or is it a different structure where the parent id's are all mixed with the children? I can only give you hints without you clarifying your structure.
CodePudding user response:
You can you have to select a One to many relation in model.
public function childs()
{
return $this->hasMany(Menu::class, 'menu_parentid', 'menu_id');
}
Then, you can select items with this query,
Menu::with('childs')->distinct()->get();