Mis*_*mad 3 php pivot-table laravel laravel-eloquent
我有一个用户模型,其中包含 id、name、email 和
包含列 id、name、code 和
数据透视表 course_user。
Course 和 User 是多对多的关系
course_user 表包含列 course_id、user_id、section
在参加课程时,一些用户将在数据透视部分列中列为“待定”,而一些用户将在部分列中列为“A”、“B”等。
问题:我想获得至少由一位用户参加的课程,并且部分是“待定”到目前为止,我已经尝试了这些:在课程模型中:
public function users(){
return $this->belongsToMany(User::class)
->withPivot('section');
->wherePivot('section', 'Pending');
}
Run Code Online (Sandbox Code Playgroud)
我在课程模型中尝试过的另一种方法:
public function pendingUsers(){
return $this->belongsToMany(User::class)
->withPivot('section')
->wherePivot('section', 'like', 'Pending');
}
Run Code Online (Sandbox Code Playgroud)
但所有这些都给了我所有的课程。现在,如何完成这项工作?
定义关系:
public function users()
{
return $this->belongsToMany(User::class)->withPivot('section');
}
Run Code Online (Sandbox Code Playgroud)
然后:
Course::whereHas('users', function($q) {
$q->where('course_user.section', 'Pending');
})
->get();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7070 次 |
| 最近记录: |