How can nested sets be used to create a hierarchical structure for a referral system in PHP?

Nested sets can be used to create a hierarchical structure for a referral system in PHP by representing each node as a range of left and right values in the database. This allows for efficient querying of parent-child relationships and easy traversal of the tree structure. By using nested sets, we can easily determine the hierarchy of referrals and calculate commissions based on the depth of the referral.

// Assuming we have a database table called 'referrals' with columns 'id', 'left_value', 'right_value', and 'user_id'

// Function to add a new referral to the nested set
function addReferral($parent_id, $user_id) {
    // Find the right-most child of the parent node
    $right_value = DB::table('referrals')->where('id', $parent_id)->value('right_value');
    
    // Update the left and right values of existing nodes
    DB::table('referrals')->where('right_value', '>', $right_value)->increment('right_value', 2);
    DB::table('referrals')->where('left_value', '>', $right_value)->increment('left_value', 2);
    
    // Insert the new referral node
    DB::table('referrals')->insert([
        'user_id' => $user_id,
        'left_value' => $right_value,
        'right_value' => $right_value + 1
    ]);
}