I have a User Model with the columns id, name, email and
a Course Model with the columns id, name, code and
a pivot table course_user.
Course and User has many-to-many relation
course_user table contains columns course_id, user_id, section
While taking courses, some users will be listed as 'Pending' in pivots section column and some users will be listed as 'A', 'B' etc in section column.
Question: I want to get those courses which are taken by at least one user and section is 'Pending' So far, I've tried these: In Course Model :
public function users(){
return $this->belongsToMany(User::class)
->withPivot('section');
->wherePivot('section', 'Pending');
}
Another Approach I've tried in course Model:
public function pendingUsers(){
return $this->belongsToMany(User::class)
->withPivot('section')
->wherePivot('section', 'like', 'Pending');
}
But all of these are giving me all of the courses. Now, How can this job be done?
Define the relationship:
public function users()
{
return $this->belongsToMany(User::class)->withPivot('section');
}
Then:
Course::whereHas('users', function($q) {
$q->where('course_user.section', 'Pending');
})
->get();
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments