问题
The below query is with lots of join table and DB::raw query, Which is working as expected. I would like to groupBy a "landing" which is a field in the table has URL stored. But I would like to groupBy URL without parameter. How can I achieve this?
Query below trying to use SUBSTRING_INDEX but didn't worked.
$adverts = DB::table('adverts')
->select(DB::raw('count(*) as total'),DB::raw('(SELECT DATE_FORMAT(max(instances.date), \'%d-%m-%Y\') FROM instances WHERE instances.ad_uid = adverts.ad_uid ORDER BY id DESC limit 1) AS Last_seen_date,'
. '(SELECT instances.country FROM instances WHERE instances.ad_uid = adverts.ad_uid ORDER BY id DESC limit 1) AS country,'
. '(SELECT advertsstorage.filename FROM advertsstorage where uid_dir = adverts.ad_uid ORDER BY id ASC limit 1) AS filename,'
.'(SELECT IF(ext = \'jpeg\', CONCAT(fullpath, \'_1.\', ext), (CONCAT(fullpath,\'.\',ext))) as fullpath FROM advertsstorage where uid_dir = adverts.ad_uid ORDER BY id ASC limit 1)as fullpath, adverts.*'))
->join('domains','adverts.domain', '=' ,'domains.domain')
->join('advertiser_domains','domains.id', '=' ,'advertiser_domains.domain_id')
->join('advertisers','advertiser_domains.advertiser_id', '=' ,'advertisers.u_id')
->where('advertisers.u_id', '=',$advertiserID)
->orderBy('Last_seen_date', 'DESC')
->groupBy(DB::raw("SUBSTRING_INDEX(adverts.landing,'?',1)"))
->get();
回答1:
I think I figured it out, and now it makes sense to me that Laravel doesn't offer parameterization with groupBy
.
First, I needed a refresher on MySql Group By.
Every field mentioned in your select
needs to be compatible with what you put in your groupBy
.
And you can use:
->groupBy(DB::raw('some_alias'))
In my case:
$statsQuery = DB::table('contacts')
->selectRaw("SUBSTR(DAYNAME(CONVERT_TZ(created_at, 'UTC', ?)), 1, 3) AS 'DayOfWeek', HOUR(CONVERT_TZ(created_at, 'UTC', ?)) AS 'Hour', COUNT(id) AS 'CallsScheduled'", [$reportingClientTimeZone, $reportingClientTimeZone])
->whereIn('adId', $adIds)
->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
->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
->whereNotNull('clarityCallTimeUtc')
->groupBy(DB::raw("DayOfWeek, Hour"));
See how COUNT()
is my only aggregate function? And the only other fields mentioned in my select
are the ones I use (the aliases of) in the groupBy
.
I think this is working for me.
来源:https://stackoverflow.com/questions/38262133/in-laravel-how-to-groupby-url-without-parameter-in-the-query