1

从普通 sql 更改查询时遇到问题(注意:我使用的不是 AR,而是续集)

所以这有效:

Post.fetch(
    "SELECT
      COUNT(*) as count, HOUR(created_at) as date, class_type
    FROM
      tours t
    WHERE
      t.created_at Between ? and ?
    GROUP BY hour(t.created_at), flavor", @range_begins, @range_ends
    ).all

它返回预期的数组。但这不是:

Post.select("COUNT(*) as count, HOUR(created_at) as date, class_type")
    .where(created_at: @basic_range)
    .group_by("HOUR(created_at), flavor")
    .all

但是在控制台中(没有 .all 结尾)从中生成的查询看起来不错(格式化以便更好地阅读):

<Sequel::Mysql2::Dataset:
"SELECT
  'COUNT(*) as count, HOUR(created_at) as date, class_type'
FROM
  `posts`
WHERE
  ((`created_at` >= '2014-05-01 00:00:00') AND (`created_at` <= '2014-05-01 23:59:59')) 
GROUP BY
  'HOUR(created_at), flavor'">

在末尾添加“.all”会返回一个如下所示的数组:

[#<Tour @values={:"COUNT(*) as count, HOUR(created_at) as date, class_type"=>"COUNT(*) as count, HOUR(created_at) as date, class_type"}>]

我错过了什么?在此先感谢您的帮助

4

1 回答 1

4

当你用where函数编写查询时,你不需要写.all在最后,它默认会给出所有匹配查询参数的结果。你只需要这样做:

Post.select("COUNT(*) as count, HOUR(created_at) as date, class_type")
    .where(created_at: @basic_range)
    .group_by("HOUR(created_at), flavor")
于 2014-05-01T07:40:48.500 回答