Golden Boy
Golden Boy

Reputation: 41

Get all child, grandchild in recursive tree

I have this problem where i can only get the direct child of a parent right now, where i need to get all the child and grandchild from the parent data, the result should be like this

Expected Result

Here's the current code that i'm use right now

public function tree_view(Request $request){
    
    $data = DB::table('users')
            ->select('id', 'username', 'referral', 'name')
            ->get();

    foreach($data as $key => $value){
         
        $item = \DB::table('users')
        ->where('referral', $value->username); 
        
        $downline = $item->count(); 
        
        
        $data[$key]->downline = $downline;  # Total Downline  
    }
    
    return view('admin.tree_view', ['data'=> $data]);
}

and this is the database structure (all data is from same table (users))

enter image description here

Upvotes: 1

Views: 176

Answers (1)

baleghsefat
baleghsefat

Reputation: 302

I recommend using this package.

Read the document of this package. You can get all parents, children, ancestors, descendants. You must just add three columns to the table. And after that execute this code in php artisan tinker :

User::fixTree();

Then you can use the capabilities of this package.

Upvotes: 1

Related Questions