如何从laravel中具有父ID的集合创建嵌套数组



我想创建一个嵌套数组来维护父子关系通过使用它们的parent_id插入嵌套数组。注意:我使用了相同的表格来保存所有类别数据。

$catItems= ProductCategory::all()->toArray();
$source = array();
foreach($catItems as $key => $value) {
$source[$key] = $value;
} 

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

$nested = array();

foreach ($source as &$s) {
if(is_null($s['parent_id']) ) {
// no parent_id so we put it in the root of the array
$nested[] = &$s;
}
else {
$pid = $s['parent_id'];
if ( isset($source[$pid])) {
// If the parent ID exists in the source array
// we add it to the 'children' array of the parent after initializing it.

if ( !isset($source[$pid]['children']) ) {
$source[$pid]['children'] = array();
}
$source[$pid]['children'][] = &$s;
}
}
}

如果我做dd($source(,我会得到以下输出

array:3 [▼
0 => array:8 [▼
"id" => 5
"name" => "Electronics"
"status" => 1
"parent_id" => null
"created_by" => 1
"updated_by" => null
"created_at" => "2021-05-06T06:32:37.000000Z"
"updated_at" => "2021-05-06T06:32:37.000000Z"
]
1 => array:8 [▼
"id" => 6
"name" => "tv"
"status" => 1
"parent_id" => 5
"created_by" => 1
"updated_by" => null
"created_at" => "2021-05-06T06:33:00.000000Z"
"updated_at" => "2021-05-06T06:33:00.000000Z"
]
2 => array:8 [▼
"id" => 7
"name" => "Home appliances"
"status" => 1
"parent_id" => null
"created_by" => 1
"updated_by" => null
"created_at" => "2021-05-06T06:33:16.000000Z"
"updated_at" => "2021-05-06T06:33:16.000000Z"
]
]

如果我执行dd($nested(,我将获得唯一的父数组,如下所示:

array:2 [▼
0 => & array:8 [▼
"id" => 5
"name" => "Electronics"
"status" => 1
"parent_id" => null
"created_by" => 1
"updated_by" => null
"created_at" => "2021-05-06T06:32:37.000000Z"
"updated_at" => "2021-05-06T06:32:37.000000Z"
]
1 => & array:8 [▼
"id" => 7
"name" => "Home appliances"
"status" => 1
"parent_id" => null
"created_by" => 1
"updated_by" => null
"created_at" => "2021-05-06T06:33:16.000000Z"
"updated_at" => "2021-05-06T06:33:16.000000Z"
]
]

创建此函数以访问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');
}