2016-04-03 127 views
3

我在Laravel雄辩中遇到了一个问题,当我运行查询并且生成的查询似乎不是我期望的结果时,我得不到结果。高级Where子句在Laravel

这是在控制器代码:

$lastUpdate = Input::get('last_update'); 
$userId = Auth::user()->id; 

$eventIds = EventVendor::where('user_id', $userId) 
        ->where('is_active', 1)->get()->lists('event_id'); 

$events = EventDetails::whereIn('id', $eventIds) 
        ->where(function($query) use ($lastUpdate) { 
         $query->where('created_at', $lastUpdate); 
         $query->orWhere('updated_at', $lastUpdate); 
        }) 
        ->where('is_active', 1) 
        ->with("details_sub") 
        ->with("extras") 
        ->with("chargesDiscounts") 
        ->toSql(); 

这是生成的查询:

select * from `mtgh_event_details` 
    where `mtgh_event_details`.`deleted_at` is null 
     and 0 = 1 
     and (`created_at` = ? or `updated_at` = ?) 
     and `is_active` = ? 

除了这是不应该在那里我看不到0 = 1完整的查询要么。

+0

“0 = 1”是否实际显示在您的查询中,或者是您为该问题更改了哪些内容? – patricus

+0

它显示在我的查询中。 – user3718908

回答

1

所以我找到了问题,查询

$eventIds = EventVendor::where('user_id', $userId) 
        ->where('is_active', 1)->get()->lists('event_id'); 

现在回来null或空列表显然这一部分,因此0 = 1我的查询。另外在另一个答案的帮助下,我能够简化我的代码,谢谢。 :)

3

0 = 1正在显示,因为填充您的$eventIds的查询未返回任何结果,因此您的Collection为空。如果将空数组(或Collection)传递给whereIn(),则它通过在0 = 1中添加快捷方式查询,因为搜索where id in()是无效的SQL,并且在空集合中进行逻辑搜索将总是返回无结果。这个快捷方式在4.2.17中添加了this pull request

至于查询的其余部分,一切看起来都正常。 with()语句正在设置预加载,它使用单独的SQL语句;它不使用连接。

所以,既然你有三个with()语句,你实际上将运行4个单独的查询,一个让你EventDetails,然后每一个加载您details_subextraschargesDiscounts用于加载的事件细节。

由于它们是单独的查询,它们不会显示在toSql()输出中。


其他说明:

  • 当获得的事件ID,你并不需要调用->get()->lists(),你可以简单地调用查询->lists()。如果您首先拨打get(),它会将全部对象加载到Collection中,然后您在Collection上调用lists()。您可以通过在查询本身上调用lists()来避免首先加载完整的Collection

  • 假设你有关系设置,你可以避免最初的查询来获取ID。您可以改用whereHas() method。您的查询将如下所示:

    $lastUpdate = Input::get('last_update'); 
    $userId = Auth::user()->id; 
    
    // assumes a relationship named 'vendor' 
    $events = EventDetails::whereHas('vendor', function($query) use ($userId) { 
          // $query is query for the EventVendors 
          $query->where('user_id', $userId)->where('is_active', 1) 
         }) 
         ->where(function($query) use ($lastUpdate) { 
          $query->where('created_at', $lastUpdate); 
          $query->orWhere('updated_at', $lastUpdate); 
         }) 
         ->where('is_active', 1) 
         ->with("details_sub") 
         ->with("extras") 
         ->with("chargesDiscounts") 
         ->toSql(); 
    
+0

user3718908我已更新我的答案,以提供有关您的0 = 1问题的一些信息。 – patricus