2016-11-14 67 views
0

用戶遞歸關係具有贊助商:與範圍

public function sponsor() 
{ 
    return $this->belongsTo(User::class, 'sponsor_id'); 
} 

用戶具有推介:

public function referrals() 
{ 
    return $this->hasMany(User::class, 'sponsor_id'); 
} 

用戶被認爲是當它們具有2個或多個轉介封端:

public function activeReferrals() 
{ 
    return $this->referrals()->whereActive(true); 
} 

public function isCapped() 
{ 
    return $this->activeReferrals()->count() >= 2; 
} 

用戶可以給點。默認情況下,贊助商將收到它們,但如果贊助商被封頂,我希望這些積分可以轉到贊助商的不受限制的轉介。如果所有的推薦都有上限,那麼它與下面的級別(推介的推薦)做同樣的事情。

如果我通過用戶爲每個用戶進行數據庫調用而去用戶,這將需要很長時間。 如何編寫一個作出遞歸調用的作用域,直到找到樹中未封頂的第一個主動引用?

這就是我想要做的事:

回答

1

請試試這個......我相信這會爲你工作:)

public function scopeNotCappedActiveReferrals($query, $count) { 
    return $query->withCount(['referrals' => function($q) { 
    $q->where('active', true); 
    }])->where('referrals_count', '<', $count); 
} 

對於第二部分。 ..

// Finally you can call it with 
public function allReferrals() { 
    $users = User::notCappedActiveReferrals(2)->get(); 

    $allUsers = $this->findNotCappedActiveReferralsRecurrsively($users); 
} 

// Do not place this function in the model, 
// place it in your Controller or Service or Repo or blahblah... 
// Also, not tested... but should work :) 
protected function findNotCappedActiveReferralsRecurrsively($users) { 
    if(!count($user)) { 
    return $users; 
    } 

    foreach($users as $user) { 
    $moreUsers = $user->notCappedActiveReferrals(2)->get(); 

    return $users->merge($this->findNotCappedActiveReferralsRecurrsively($moreUsers)); 
    } 
} 

希望這是你所需要的:)

+0

我試圖找到沒有上限的人,所以我把它改成了'where('referrals_count','<',$ count)'。這在第一級(發起人的推薦)上工作得很好。它能夠找到一個活動用戶,其活動引用少於2個。 問題是,我將如何去檢查下一個級別?第一個返回空數組,因爲沒有活動用戶的活動引用少於2個。我該如何讓這件事情一路順風,但在找到符合條件的用戶時停下來? – johnRivs

+0

是的,對於錯誤的「小於/大於」符號進行操作。修正了我的答案。其次,你可以簡單地運行一個遞歸函數來查找所有的用戶....但是。我不確定這裏需要什麼,但看看我編輯的答案......也許這就是你真正想要的:) – prateekkathal

+0

我不想在整個數據庫中找到所有不是封頂。我需要找到第一個活躍的,而不是在當前的「水平」上限。如果沒有找到,然後跳轉到下面的級別,然後再試一次,等等。直到只有1返回。 – johnRivs