【问题标题】:Laravel Eleqent How to use DATE_FORMAT in PostgresqlLaravel Eloquent 如何在 Postgresql 中使用 DATE_FORMAT
【发布时间】:2019-10-01 18:43:22
【问题描述】:

我正在编写一个查询来获取按 created_at 分组的记录,下面是我的查询。

$q = Post::where('user_id', '=', auth()->user()->id)
                ->orderBy('created_at', 'desc')
                ->groupBy(DB::raw("DATE_FORMAT(created_at, '%Y-%m-%d')"))
                ->take(10)
                ->get(array(
                    DB::raw('Date(created_at) as date'),
                    DB::raw('COUNT(id) as "views"')
                ))->reverse()

这在 mysql 上运行没有任何错误,但是当我使用 postgresql 在 heroku 上推送代码时,我得到错误:

ERROR:  function date_format(timestamp without time zone, unknown) does not exist

【问题讨论】:

  • 是否应该在 MySQL 和 PostgreSQL 上运行相同的代码?

标签: laravel postgresql eloquent


【解决方案1】:

我知道这已经很晚了,但是如果有人仍然在这里寻找答案是如何在 Postgresql 中获取日期,您可以使用 field_name::date,例如 created_at::date

上面的查询可以写成

DB::select("select created_at::date, COUNT(id) as views from post where user_id = ".auth()->user()->id." group by created_at::date order by created_at desc Limit 10");

【讨论】:

    猜你喜欢
    • 2020-01-06
    • 2019-10-19
    • 2012-08-16
    • 2018-03-02
    • 2021-02-24
    • 2016-09-28
    • 1970-01-01
    • 2021-09-09
    • 2014-04-17
    相关资源
    最近更新 更多