我在类别类中具有以下功能:
...
/**
* 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;
}
...
当我调用getTheCategory
函数时,会得到以下结果:
[
{
"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": []
}
]
现在,如何将children_recursive
更改为children
?我想要这样的结果:
[
{
"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": []
},
...
]
答案 0 :(得分:-1)
您应该使用laravel的访问器和别名来执行此操作。在此处https://laravel.com/docs/5.7/eloquent-mutators#defining-an-accessor中查看减损。