[英]These Laravel query bindings don't work
Why are my Laravel query bindings not working? 为什么我的Laravel查询绑定不起作用?
This query works in MySqlWorkbench: 此查询在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
Here is my Laravel code. 这是我的Laravel代码。 Unfortunately, it returns an empty array (unlike the raw MySql above, which returns correct results):
不幸的是,它返回一个空数组(与上面的原始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());
I've also tried using 'named bindings' as shown in the docs . 我也尝试使用docs中所示的“命名绑定”。
Interestingly, when I comment out the 2 whereRaw
lines, I do get a resulting array (although it's incorrect). 有趣的是,当我注释掉2条
whereRaw
,确实得到了一个结果数组(尽管它是错误的)。
According to DB::getQueryLog()
, the bindings look good; 根据
DB::getQueryLog()
,绑定看起来不错; here is the log output: 这是日志输出:
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
]
]
Here is the query that ended up working for me. 这是最终为我工作的查询。 No quotes around the
?
周围没有引号
?
. 。
$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();
Thanks, @Razor. 谢谢,@剃刀。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.