我有一个类似于的用户表:
=== users ===
id: int (PK)
name: string
is_coach: bool
...
和一个类似于:
的教练请求表=== coach_requests ===
id: int (PK)
student_id: int(FK => users.id)
coach_id: int(FK => users.id)
...
我也有相应的Laravel模型(例如User
和CoachRequest
)。
在User
模型中,我希望创建一个方法,以便在给定指定用户的情况下,使用is_coach = true
返回所有用户,但不包括:
coach_requests
表中与该人匹配的用户。例如,请考虑以下示例数据:
用户
(1, "A", false)
(2, "B", true)
(3, "C", true)
(4, "D", true)
(5, "E", true)
(6, "F", true)
coach_requests
(1, 2, 3)
(2, 2, 4)
(3, 3, 2)
(4, 3, 6)
(5, 4, 5)
(6, 4, 6)
(7, 5, 6)
(8, 6, 5)
(9, 1, 4)
现在,如果我是用户:
我怎样才能使用Laravel?
到目前为止我只有这个:
public function scopeOfFreeCoaches($query) {
return $query->where([
'is_coach' => true,
]);
}
所以不多!
非常感谢!
答案 0 :(得分:3)
感谢@purpleninja原始查询,我设法弄清楚如何使用Laravel执行此操作:
public function getPotentialCoaches()
{
return
User::where('is_coach', true)
->where('id', '<>', $this->id)
->whereNotIn('id', function ($query) {
$query->select('coach_id')
->from('coach_requests')
->where('student_id', $this->id);
})
->get();
}
答案 1 :(得分:1)
这是我头脑中的原始查询:
SELECT u.id FROM users AS u
WHERE u.is_coach = true
AND u.id <> ’$userId’
AND u.id NOT IN(
SELECT student_id FROM coach_requests
WHERE coach_id = ’$userId’
)
快速完成并且未经过测试,因此您可能需要稍微更改一下。