I have these functions in my Category Class:
...
/**
* Get the children of current category.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function children()
{
return $this->hasMany(Category::class, 'parent_id');
}
/**
* Get the nested children of current category.
*
* @return @return \Illuminate\Database\Eloquent\Builder
*/
public function childrenRecursive()
{
return $this->children()->with('childrenRecursive');
}
/**
* Get the category that depends with the given group name.
*
* @param string $group
* @return \Illuminate\Database\Eloquent\Collection|null
*/
public static function getTheCategory($group)
{
$root = Category::where('group', $group)->whereNull('parent_id')->first();
return $root ? $root->childrenRecursive()->get() : null;
}
...
When I call the getTheCategory
function I get this result:
[
{
"id": 2,
"title": "Agricultural",
"concise": "The category for agricultural products.",
"created_at": "2019-12-17 18:01:05",
"updated_at": "2019-12-17 18:01:05",
"children_recursive": []
},
{
"id": 3,
"title": "Animal",
"concise": "The category for animal products.",
"created_at": "2019-12-17 18:01:05",
"updated_at": "2019-12-17 18:01:05",
"children_recursive": []
},
{
"id": 4,
"title": "Handicrafts",
"concise": "The category for handicrafts products.",
"created_at": "2019-12-17 18:01:05",
"updated_at": "2019-12-17 18:01:05",
"children_recursive": []
}
]
Now, how can I change the children_recursive
to the children
? I want the result like this:
[
{
"id": 2,
"title": "Agricultural",
"concise": "The category for agricultural products.",
"created_at": "2019-12-17 18:01:05",
"updated_at": "2019-12-17 18:01:05",
"children": []
},
...
]
as
method? something like$this->children()->with('childrenRecursive')->as('children');
as
method is for belongsToMany and it renames the pivot objecttoArray
function.