you need to fetch all the products in one query and then process them to build the tree. You cant eager load it the traditional way. Original solution from Formatink
public function products($projectId)
{
$products= Product::where('project_id', $projectId)->get();
$products_by_id = collect();
foreach ($products as $product) {
$products_by_id->put($product->id, $product);
}
foreach ($products as $key => $product) {
$products_by_id->get($product->id)->children = new Collection;
if ($product->parent_id != 0) {
$products_by_id->get($product->parent_id)->children->push($product);
unset($products[$key]);
}
}
return $products;
}
19
solved How can show unlimited parent-child & sub-child tree data in laravel