我有 2 个表,例如“用户”和“类(class)”。 我想要选择已通过两门类(class)的用户。
user
id username
1 John
2 Jane
courses
id name user_id
1 course-1 1
2 course-2 1
3 course-1 2
我使用:
(new User)->join('courses', 'courses.user_id', '=', 'user.id')
->whereIn('courses.name', ['course-1','course-2'])
但是此查询返回 2 个用户而不是 1 个(仅 john)。我想要 whereIn 返回 AND 连接而不是 OR 连接。
我想要这样的:
SELECT * from user
join courses as c1 on c1.user_id = user.id
join courses as c2 on c2.user_id = user.id
where c1.name = 'course-1' and c2.name = 'course-2'
在 Laravel 中会怎样?
最佳答案
使用这个:
User::join('courses as c1', 'c1.user_id', '=', 'user.id')
->join('courses as c2', 'c2.user_id', '=', 'user.id')
->where('c1.name', 'course-1')
->where('c2.name', 'course-2')
顺便说一句:您应该使用 Eloquent relationships对于这样的情况。
关于php - Laravel 查询生成器选择具有不同条件的同一表同一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50339445/