2016-01-19 109 views
1

我正在使用Laravel查詢生成器編寫連接語句,並且發現我遇到了一個奇怪的錯誤。當我從phpmyadmin運行下面的查詢時,它可以工作,但當我嘗試訪問Laravel中的頁面時出現錯誤。Laravel查詢生成器加入錯誤。 SQLSTATE [42000]錯誤

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; 
check the manual that corresponds to your MySQL server version for the right syntax to use near 
'? where `entities`.`deleted_at` is null' at line 1 (SQL: select * from `entities` inner join 
`entity_contact_info` on `entity_contact_info`.`entity_id` = `entities`.`id` and `entities`.`sector_id` 
= 2 and `entity_contact_info`.`country_id` IN (select `id` from countries WHERE `region_id` = 9) 
where `entities`.`deleted_at` is null) 

我在Laravel中構建的查詢如下。再一次,當我從上面的錯誤複製查詢並運行它時,它可以工作。似乎沒有理由爲什麼這不起作用。

$query = Entity::Join("entity_contact_info", function ($join){ 
       $join->on("entity_contact_info.entity_id", "=", "entities.id") 
        ->where("entities.sector_id", "=", "2") 
        ->where("entity_contact_info.country_id", "IN", "(select `id` from countries WHERE `region_id` = 9)"); 
       })->get(); 

有什麼建議嗎?

回答

0

我會說問題在於你的第二條where()聲明。

請嘗試以下操作。

->where("entity_contact_info.country_id", "IN", DB::raw("(select `id` from countries WHERE `region_id` = 9)")) 
+0

可悲的是這並沒有奏效。仍然不知道爲什麼。 –

0

試試這個,

$query = Entity::Join("entity_contact_info", function ($join){ 
       $join->on("entity_contact_info.entity_id", "=", "entities.id") 
        ->where("entities.sector_id", "=", "2") 
        ->whereIn("entity_contact_info.country_id", DB::raw("(select `id` from countries WHERE `region_id` = 9)")); 
       })->get(); 

的另一種方式,

$query = Entity::Join("entity_contact_info", function ($join) { 
       $join->on("entity_contact_info.entity_id", "=", "entities.id") 
       ->where("entities.sector_id", "=", "2") 
      ->whereIn('entity_contact_info.country_id', function($query) { 
       $query->select('id') 
        ->from('countries') 
        ->where('countries.region_id = 9'); 
      }) 
     })->get(); 

Use of where IN laravel

+0

我試過這個,但我得到以下錯誤:參數2傳遞給Illuminate \ Database \ Query \ JoinClause :: whereIn()必須是類型數組,對象給出 –

+0

@TonyOlendo你試過第一或第二的方式?你可以嘗試像這樣'DB :: raw(「(從國家選擇id where region_id = 9)」) - > toArray()' –

+0

感謝您的持續幫助。我嘗試了兩個建議,最近的評論會產生以下錯誤:調用未定義的方法Illuminate \ Database \ Query \ Expression :: toArray() –

相關問題