如何使用laravel中的父ID从集合创建嵌套数组?

如何使用laravel中的父ID从集合创建嵌套数组?,laravel,Laravel,我想创建一个维护父子关系的嵌套数组 通过使用它们的父\u id。我希望生成以下查询结果 NB:我使用同一个表来保存所有类别数据 我应用了以下方法来创建嵌套数组 如果我执行dd($source),我将得到以下输出 如果我使用dd($nested),我将得到唯一的父数组,如下面所示: 创建此函数以访问ProductCategory.php文件中的子项: public function children() { return $this->hasMany(ProductCategory:

我想创建一个维护父子关系的嵌套数组 通过使用它们的父\u id。我希望生成以下查询结果 NB:我使用同一个表来保存所有类别数据

我应用了以下方法来创建嵌套数组

如果我执行dd($source),我将得到以下输出

如果我使用dd($nested),我将得到唯一的父数组,如下面所示:


创建此函数以访问ProductCategory.php文件中的子项:

public function children()
{
    return $this->hasMany(ProductCategory::class, 'parent_id');
}
在控制器中:

$cartItems = ProductCategory::with('children')->get();
如果要获取任何子类别的父级:

public function parent()
{
    return $this->belongsTo(ProductCategory::class, 'parent_id');
}
你可以这样得到它的父母

public function parent()
{
    return $this->belongsTo(ProductCategory::class)->with('parent');
}

谢谢你的回复。我忘了提到我只有一张桌子。我知道这个代码只针对一张桌子。试试看
public function children()
{
    return $this->hasMany(ProductCategory::class, 'parent_id');
}
$cartItems = ProductCategory::with('children')->get();
public function parent()
{
    return $this->belongsTo(ProductCategory::class, 'parent_id');
}
public function parent()
{
    return $this->belongsTo(ProductCategory::class)->with('parent');
}