Closed juliomotol closed 1 year ago
Can you please show me the MenuResource
implementation?
Here you go
class MenuResource extends JsonApiResource
{
public function toAttributes($request): array
{
return [
'name' => $this->name,
];
}
public function toRelationships($request): array
{
return [
'nodeTrees' => fn () => NodeResource::collection($this->nodeTrees),
];
}
}
// and
class NodeResource extends JsonApiResource
{
public function toAttributes($request): array
{
return [
'label' => $this->label,
'url' => $this->url,
'target' => $this->target,
];
}
public function toRelationships($request): array
{
return [
'children' => fn () => NodeResource::collection($this->children),
];
}
}
Does the following result in the expected relationships,..
/menus/9999?include=nodeTree.children
Tried that but it only responds with up to the second level of the tree:
array:6 [ // app/HttpTenantApi/Controllers/Menu/MenuController.php:30
"id" => 1
"name" => "Menu"
"node_trees" => array:1 [
0 => array:10 [
"id" => 1
"label" => "Node 1 "
"menu_id" => 1
"parent_id" => null
"order" => 1
"children" => array:1 [ // included in the response
0 => array:10 [
"id" => 2
"label" => "Nested Node 1"
"menu_id" => 1
"parent_id" => 1
"order" => 1
"children" => array:1 [ // not returned in the response
0 => array:10 [
"id" => 3
"label" => "Deeply Nested Node"
"menu_id" => 1
"parent_id" => 2
"order" => 1
"children" => []
]
]
]
]
]
]
]
So the issue here is that your model relationships are not setup to return all of the tree.
I recommend using this package to add a relationship to your model that may be included and will return all of the expected results: https://github.com/staudenmeir/laravel-adjacency-list
I initially tried that, but gave up halfway. I'll try to fiddle with it more and get back to you. Thanks!
Sounds good.
We have a
Menu
andNode
models where aMenu
has manyNode
s and aNode
also has many childNode
s.Then our controller action:
Now, when we try to
/menus/9999?include=nodeTree
, it only responds with the root nodes and doesn't show the child nodes nested in them. When try to inspect the model before MenuResource::make(), we do see whole node tree.Any ideas on how this could be done?