2016-01-19 86 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() –

相关问题