Ryan
Ryan

Reputation: 24035

These Laravel query bindings don't work

Why are my Laravel query bindings not working?

This query works in 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. Unfortunately, it returns an empty array (unlike the raw MySql above, which returns correct results):

$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.

Interestingly, when I comment out the 2 whereRaw lines, I do get a resulting array (although it's incorrect).

According to DB::getQueryLog(), the bindings look good; 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
  ]
]

Upvotes: 0

Views: 615

Answers (1)

Ryan
Ryan

Reputation: 24035

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.

Upvotes: 1

Related Questions