2016-08-12 78 views
0

我想建立查詢在laravel後5內建laravel複雜查詢5

SELECT * FROM tbl WHERE updated_at IN (
    SELECT max(updated_at) FROM tbl 
    WHERE created_at BETWEEN $begin_time AND $end_time 
    GROUP BY ip_address) 

我的代碼:

$sqlStr = self::select('*') 
     ->whereIn('updated_at', function($query){ 
         return $query->select(self::raw('max(updated_at)')) 
          ->whereRaw('created_at >= $begin_time) 
          ->whereRaw('created_at <= $end_time) 
          ->groupBy('ip_address'); 
})->toSql(); 
var_dump(($sqlStr));die; 

錯誤信息:

ErrorException在Grammar.php線58:
strtolower()期望參數1是字符串,給定的對象

請幫幫我。

+0

是你的$ BEGIN_TIME和$ END_TIME字符串或碳日期?你也應該使用綁定參數而不是連接字符串來插入變量,這樣你會更安全,並且你將避免你在這裏可能遇到的問題,在whereRaw語句中缺少' – rypskar

回答

0

當您編寫self::raw('max(updated_at)')時,它會生成SELECT max(updated_at) FROM tbl,它已經在select命令中。下面的代碼將工作:

$sqlStr = self::select('*') 
    ->whereIn('updated_at', function($query) { 
     $query->selectRaw('max(updated_at)') 
      ->from('tbl') 
      ->whereRaw('created_at >= $begin_time') 
      ->whereRaw('created_at <= $end_time') 
      ->groupBy('ip_address'); 
})->toSql(); 
0

或者這應該工作太:

DB::select(
    'SELECT * FROM tbl WHERE updated_at IN (' . 
     'SELECT max(updated_at) FROM tbl ' . 
     'WHERE created_at BETWEEN :begin_time AND :end_time ' . 
     'GROUP BY ip_address ' 
    ')', 
    [ 
     'begin_time' => $begin_time, 
     'end_time' => $end_time 
    ] 
);