如何在Laravel模型关系中使用“where not”?

时间:2016-03-07 01:32:33

标签: php sql laravel model laravel-5

我有一个类似于的用户表:

=== 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模型(例如UserCoachRequest)。

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)

现在,如果我是用户:

  • id 1(即用户“A”),返回用户ID:2,3,5和6
  • id 2,返回用户ID:5,6
  • id 3,返回用户ID:4,5
  • id 4,返回用户ID:2,3
  • id 5,返回用户ID:2,3,4
  • id 6,返回用户ID:2,3,4

我怎样才能使用Laravel?

到目前为止我只有这个:

public function scopeOfFreeCoaches($query) {
    return $query->where([
        'is_coach' => true,
    ]);
}

所以不多!

非常感谢!

2 个答案:

答案 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’
)

快速完成并且未经过测试,因此您可能需要稍微更改一下。