Laravel查询其中value等于另一个表中的值

时间:2014-11-24 13:26:54

标签: laravel laravel-4

我正在尝试使用查询生成器进行查询。我试图使where关闭,以便根据另一个where子句选择与另一个表中存储的值相等的值。

让我解释一下,我有这张桌子:

select negotiation_id, status_id from negotiations_statuses;
+----------------+-----------+
| negotiation_id | status_id |
+----------------+-----------+
|              1 |         1 |
|              2 |         1 |
|              3 |         1 |
|              4 |         1 |
|              5 |         1 |
|              6 |         1 |
+----------------+-----------+

这张表:

select * from statuses;
+----+------------+
| id | name       |
+----+------------+
|  1 | open       |
|  2 | in_process |
|  3 | completed  |
|  4 | rejected   |
+----+------------+

我想选择不是completedrejected的协商。

这就是我的尝试:

$items = DB::table('negotiations')
            ->join('negotiations_statuses', 'negotiations.id', '=', 'negotiations_statuses.negotiation_id')
            ->where('user_id', '=', Auth::user()->id)
            ->where('status_id', '!=', '3')
            ->where('status_id', '!=', '4')
            ->get();

它有效,但我显然是在作弊,因为我直接使用status_id。我怎样才能进行这样的嵌套查询?

1 个答案:

答案 0 :(得分:0)

$items = DB::table('negotiations')
        ->join('negotiations_statuses', 'negotiations.id', '=','negotiations_statuses.negotiation_id')
        ->whereNotExists(function($query){
             $query->where('status_id', '<>', 3)
                   ->where('status_id', '<>', 4);
        })
        ->get();

此查询将获取所有未完成或拒绝的项目。

注意:尚未经过测试。