多对多关系中的特定结果

Specific result in many to many relationship

希望能在这里找到答案, 我有一个组、用户和参与者 table,组和参与者是 link 到具有一对多关系的用户。 Np 那个。

现在我有一个 group_participant table,它应该是 link 组的参与者,有 3 列:

  1. id
  2. group_id
  3. participant_id

我想做的是获取不属于该组的参与者列表,我可以轻松获取整个列表,但我想过滤这个以便只获取那些与群组无关。

我有点受困于多对多关系,我有我的 Group.php 模型,其中包含:

    public function participantsGroup()
{
    return $this->belongsToMany('App\Participant');
}

如果我这样做:

public function participants(){

    $group = Group::find('group_id_there')->participantsGroup;
    return $group;
}

我正在获取与该组相关的参与者列表,但我想要的是相反的,请问我该怎么做?

要完成此操作,您应该使用 whereNotIn() 方法,并传递当前参与者的数组。示例:

// Fetch the participants in the group
$groupParticipantsId = Group::find(1)->participantsGroup()->lists('participant_id');
// Query to get all participants that are not in that group
$participantsNotInGroup = App\Participant::whereNotIn($groupParticipantsId)->get();

最佳做法是在 Class 上创建一个对您更有意义的 scope,我将在 App\Participant class 上创建范围:

public function scopeNotInGroup($query, App\Group $group) {
    $participants = $group->participantsGroup()->lists('participant_id');
    return $query->whereNotIn($participants);
}

然后您可以在应用程序的任何位置执行此操作:

// Fetch the participants in the group
$group = Group::find(1);
// Query to get all participants that are not in that group
$participantsNotInGroup = App\Participant::notInGroup($group)->get();