我希望在这里找到答案,我有一个组、用户和参与者表,组和参与者链接到具有一对多关系的用户。Np。
现在我有了一个group_participant表,它应该将参与者链接到一个组,有3列:
- id
- group_id
- 参与者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();
最佳实践是在类上创建一个对您更有意义的scope
,我将在App'Participant
类上创建作用域:
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();