如何找到 Eloquent 查询的逆

How to find inverse of Eloquent query

我有一个查询要查找特定 activity 中的注册学生。在用户模型上:

public function enrolledStudents($activity)
{ 
    $students = $activity->students()
        ->wherePivot('user_id', $this->id)
        ->get();
    return $students;
}

Activity 模型的 students 方法是这样的:

public function students()
{
    return $this->belongsToMany('Student', 'activity_student', 'activity_id', 'student_id')
        ->withPivot('user_id')
        ->withTimestamps();
}

我想要另一种方法来找到 没有 注册的学生 activity - 我该怎么做?

即$user->students()->notEnrolled($activity)

基本上,您必须来自 Student 角度。像这样:

$students = Student::whereDoesntHave('activities', function($q) use ($activity){
    $q->where('activity_id', $activity->id);
})->get();

请注意,此方法很新,因此您可能需要将 Laravel 更新为 composer udpate