为什么我的Laravel查询绑定不起作用?
此查询适用于MySqlWorkbench:
SELECT
COUNT(id) AS AC_Leads,
SUM(IF(webinarMinsWatched > 0, 1, 0)) AS startedWebinar,
SUM(IF(webinarMinsWatched >= 47.23, 1, 0)) AS reachedCta
FROM
contacts
WHERE
DATE_FORMAT(created_at, '%Y-%m-%d') = '2017-05-06'
AND adId = '6000689619221'
GROUP BY adId
这是我的Laravel代码。不幸的是,它返回一个空数组(与上面的原始MySql不同,返回正确的结果):
$webinarCta = '47.23';
$adId = "6000689619221";
$dateStr = "2017-05-06";
DB::enableQueryLog();
$statsQuery = DB::table('contacts')
->selectRaw('COUNT(id) as AC_Leads, SUM(IF(webinarMinsWatched > 0, 1, 0)) as startedWebinar, SUM(IF(webinarMinsWatched >= ?, 1, 0)) as reachedCta', [(float) $webinarCta])
->whereRaw("DATE_FORMAT(created_at, '%Y-%m-%d') = '?'", [$dateStr])
->whereRaw("adId = '?'", [(int) $adId])
->groupBy('adId');
print_r($statsQuery->toSql());
echo '<hr>';
$stats = $statsQuery->get();
print_r($stats);
echo '<hr>';
Log::debug(DB::getQueryLog());
dd(DB::getQueryLog());
我还试过使用&#39;命名绑定&#39;如图所示in the docs。
有趣的是,当我注释掉2 whereRaw
行时,我会得到一个结果数组(尽管它不正确)。
根据DB::getQueryLog()
,绑定看起来很好;这是日志输出:
array:1 [▼
0 => array:3 [▼
"query" => "select COUNT(id) as AC_Leads, SUM(IF(webinarMinsWatched > 0, 1, 0)) as startedWebinar, SUM(IF(webinarMinsWatched >= ?, 1, 0)) as reachedCta from `contacts` where DATE_FORMAT(created_at, '%Y-%m-%d') = '?' and adId = '?' group by `adId` ◀"
"bindings" => array:3 [▼
0 => 47.23
1 => "2017-05-06"
2 => 6000689619221
]
"time" => 0.38
]
]
答案 0 :(得分:1)
这是最终为我工作的查询。 ?
附近没有引号。
$statsQuery = DB::table('contacts')
->selectRaw('adId, COUNT(id) as AC_Leads, SUM(IF(webinarMinsWatched > 0, 1, 0)) as startedWebinar, SUM(IF(webinarMinsWatched >= ?, 1, 0)) as reachedCta', [(float) self::WEBINAR_CTA])
->groupBy('adId');
if ($startDate) {
$statsQuery->whereRaw("CONVERT_TZ(created_at, 'UTC', ?) >= STR_TO_DATE(?, '%Y-%m-%d')", [$reportingClientTimeZone, $startDate]); //https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_convert-tz
}
if ($endDate) {
$statsQuery->whereRaw("CONVERT_TZ(created_at, 'UTC', ?) < DATE_ADD(STR_TO_DATE(?, '%Y-%m-%d'), INTERVAL 1 day)", [$reportingClientTimeZone, $endDate]); //Given a certain endDate (which begins at midnight), only include results LESS THAN 1 day after that midnight
}
$result = $statsQuery->get();
谢谢,@ Razor。