2015-07-12 72 views
1

在我的Laravel應用程序中,我有用戶,朋友和羣組的概念。用戶可以創建並將朋友分組。從Laravel的收藏中排除項目

用戶可以有很多朋友:

function friendsOfMine() 
{ 
    return $this->belongsToMany('App\User', 'helpers', 'user_id', 'helper_id') 
    ->wherePivot('accepted', '=', 1); 
} 

一個組可以有很多用戶:

public function groupMembers() 
{ 
    return $this->belongstoMany('App\User')->withTimestamps(); 
} 

在UI添加朋友一組,我想說明的完整列表一個用戶的朋友,但排除那些已經添加到該組的朋友。我的組控制器功能看起來像這樣,但我是積極的,我是非基地。

public function add($id) 
    { 
    $group = Group::findOrFail($id); 
    $helpers = $group->groupMembers; 
    $id = $helpers->lists('id'); 
    $invitees = $this->user 
     ->friendsOfMine() 
     ->where('helper_id', '!=', $id) 
     ->Paginate(5); 
    return view('groups.add', compact('group','helpers','invitees')); 
    } 

理想情況下,我很樂意爲一些方法來寫:

$helper = $group->friendsOfMine->not->groupMembers->Paginate(5); 

反正是有使用來自兩個不同型號的功能過濾數據?

回答

0

你的方法,你將不得不使用whereNotIn()因爲你有一組ID:

$id = $helpers->lists('id'); 
$invitees = $this->user 
    ->friendsOfMine() 
    ->whereNotIn('helper_id', $id) 
    ->Paginate(5); 

但是你很可能是這樣的,以及(假設關係group

$invitees = $this->user 
    ->friendsOfMine() 
    ->whereDoesntHave('group', function($q) use ($id){ 
     $q->where('group_id', $id); // Note that id is the group id (not the array of ids from the helper) 
    }) 
    ->Paginate(5); 

對於更好的語法(如你的例子),你應該看看Query Scopes

+0

工作非常好 - 感謝您的快速反應,並增加了細節。查詢範圍正是我所需要的。 –