在 Laravel 中如何在查询中不带参数的 groupBy Url
Posted
技术标签:
【中文标题】在 Laravel 中如何在查询中不带参数的 groupBy Url【英文标题】:In Laravel how to groupBy Url without parameter in the query 【发布时间】:2016-11-10 18:08:06 【问题描述】:以下查询包含大量连接表和 DB::raw 查询,按预期工作。我想 groupBy 一个“登陆”,它是表中存储了 URL 的字段。 但我想 groupBy URL 不带参数。我怎样才能做到这一点?
下面的查询尝试使用 SUBSTRING_INDEX 但没有奏效。
$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。你有没有想过如何通过参数使用 Laravel groupBy?我现在被同样的问题阻止了。谢谢! 【参考方案1】:我想我已经明白了,现在 Laravel 不提供 groupBy
的参数化对我来说是有意义的。
首先,我需要复习一下mysql Group By。
select
中提到的每个字段都需要与您在groupBy
中输入的内容兼容。
你可以使用:
->groupBy(DB::raw('some_alias'))
就我而言:
$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"));
看看COUNT()
是我唯一的聚合函数吗?我的select
中提到的唯一其他字段是我在groupBy
中使用的(的别名)。
我认为这对我有用。
【讨论】:
以上是关于在 Laravel 中如何在查询中不带参数的 groupBy Url的主要内容,如果未能解决你的问题,请参考以下文章
涉及变量引用和子表达式的参数模式中不带引号的标记:为啥它们有时会分成多个参数?