【问题标题】:Laravel Query builder select same table same column with diferent conditionLaravel Query builder选择相同的表相同的列具有不同的条件
【发布时间】:2018-10-24 15:39:37
【问题描述】:

我有 2 个表格,例如“用户”和“课程”。 我想要选择通过两门课程的用户。

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 中会怎样?

【问题讨论】:

  • 你不是说c2.user_id = user.id吗?
  • 哦,对不起,是的。谢谢。

标签: php mysql sql laravel query-builder


【解决方案1】:

使用这个:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-10
    • 2014-01-19
    • 2020-02-07
    • 1970-01-01
    • 2011-03-31
    • 1970-01-01
    • 2019-02-10
    • 2015-02-28
    相关资源
    最近更新 更多