【问题标题】:How to use "where not" in a Laravel Model Relationship?如何在 Laravel 模型关系中使用“where not”?
【发布时间】:2016-06-20 11:28:53
【问题描述】:

我有一个类似的用户表:

=== 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,
    ]);
}

不多!

非常感谢!

【问题讨论】:

  • 在这种情况下,原始查询可能是最简单的方法,因为它是一种自定义:laravel.com/docs/5.1/database
  • 我什至不确定这个原始的会是什么

标签: php sql laravel model laravel-5


【解决方案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’
)

快速完成且未经测试,因此您可能需要稍作更改。

【讨论】:

    【解决方案2】:

    感谢@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();
    }
    

    【讨论】:

      猜你喜欢
      • 2015-07-05
      • 2015-03-12
      • 2018-08-30
      • 1970-01-01
      • 2021-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多