如何在Laravel模型关系中使用“不在哪里”


How to use "where not" in a Laravel Model Relationship?

我有一个类似于以下内容的用户表:

=== 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

如何使用拉拉维尔做到这一点?

到目前为止,我所拥有的只是这个:

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

所以不多!

非常感谢!

多亏@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();
}

这是我头顶上的一个原始查询:

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

快速完成且未测试,因此您可能需要对其进行一些更改。