2014-11-24 57 views
0

我正在嘗試使用查詢生成器進行查詢。我試圖使where關閉,因此它根據另一個where子句選擇等於存儲在另一個表中的值的值。Laravel查詢其中的值等於另一個表中的值

讓我解釋一下我自己,我有這個表:

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。我怎樣才能做這樣的嵌套查詢?

+0

你想使用子查詢或嵌套的查詢嗎? – JMc 2014-11-24 13:35:50

+0

嵌套在哪裏查詢 – dabadaba 2014-11-24 13:37:02

回答

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(); 

該查詢將獲得所有未完成或拒絕的項目。

注意:這還沒有經過測試。

+0

它不起作用:SQLSTATE [42000]:語法錯誤或訪問衝突:1064您的SQL語法中有錯誤;檢查與您的MySQL服務器版本相對應的手冊,在'where status_id' <>附近使用正確的語法。和'status_id' <>?)'在第1行(SQL:select * from'negotiation'內部連接'negotiation_statuses'在'negotiation'.id' ='negotiation_statuses'.'negotiation_id'其中'user_id' = 2而不是存在(選擇*其中'status_id' <> 3和'status_id' <> 4)) – dabadaba 2014-11-24 13:51:49

+0

這也不是我想要做的,我試圖比較狀態的名稱,而不是值... – dabadaba 2014-11-24 13:53:47

+0

好吧。看起來很簡單。關於錯誤,你可以將<>更改爲!=並查看是否得到相同的錯誤? – JMc 2014-11-24 13:58:35

相關問題