You can store upline levels in your user table, too. During registration you grab upline, then upline of upline, etc so that later you can get them when querying the user table.
I do this 6 levels deep so it is 6 more queries but I don't really care, registering doesn't happen a million times a day.

Here's my user table from my traffic exchange ... hope it helps. As you can see I also use an upline_val column to store surf credits which can later be claimed by their uplines with a button "claim credits from referrals".
and register model code to create member:
$data = array(
'username' => $username,
'password' => password_hash($password, PASSWORD_DEFAULT),
'email' => $email,
'first_name' => $first_name,
'last_name' => $last_name,
'active' => $active,
'referred_by_id' => $referred_by_id,
'referral_url' => $this->session->userdata('referral_url'),
'next_subscription_update' => $now->format("Y-m-d H:i:s"),
'email_newsletter' => $newsletter,
'autoassign_pct' => Settings_model::$db_config['autoassign_value']
);
// select upline ids
$this->db->select('referred_by_id')->from(DB_PREFIX .'user')->where('user_id', $data['referred_by_id']); // $data['referred_by_id'] is passed in the url e.g. http://example.com/register/1867
$q = $this->db->get();
if ($q->num_rows() == 1) {
$data['upline_lvl2'] = $q->row()->referred_by_id;
$this->db->select('referred_by_id')->from(DB_PREFIX .'user')->where('user_id', $data['upline_lvl2']);
$q = $this->db->get();
if ($q->num_rows() == 1) {
$data['upline_lvl3'] = $q->row()->referred_by_id;
$this->db->select('referred_by_id')->from(DB_PREFIX .'user')->where('user_id', $data['upline_lvl3']);
$q = $this->db->get();
if ($q->num_rows() == 1) {
$data['upline_lvl4'] = $q->row()->referred_by_id;
$this->db->select('referred_by_id')->from(DB_PREFIX .'user')->where('user_id', $data['upline_lvl4']);
$q = $this->db->get();
if ($q->num_rows() == 1) {
$data['upline_lvl5'] = $q->row()->referred_by_id;
$this->db->select('referred_by_id')->from(DB_PREFIX .'user')->where('user_id', $data['upline_lvl5']);
$q = $this->db->get();
if ($q->num_rows() == 1) {
$data['upline_lvl6'] = $q->row()->referred_by_id;
}
}
}
}
}
// ...etc...
$this->db->insert(DB_PREFIX .'user', $data); // $data is inserted here
That's about all I can do I guess.