首页 > 解决方案 > 从 laravel 的日期字段中选择月份

问题描述

我正在尝试在 Laravel 7 中执行获取日期字段的月份部分的查询。我尝试了以下查询

$test = MyModal::selectRaw('month("date_col") as temp')->get();
$test = MyModal::select(DB::Raw('month("date_col") as temp'))->get();
$test = DB::table('my_table')->select('month("date_col") as temp')->get();

同一查询的所有变体。如果我转储查询日志,则查询对所有 3 个都是正确的

select month("date_col") as temp from "my_table"

如果我在我的数据库上运行它,我也会得到结果。但是我在laravel中不断收到这个错误:

Illuminate\Database\QueryException: SQLSTATE[HY000]: General error: 1 no such function: month (SQL: select month("date_col") as temp from "my_table")

难道我做错了什么?有没有办法在 laravel 中进行此查询?

编辑:抱歉忘了提到这是 Laravel 的单元测试

标签: phplaraveleloquent

解决方案


我认为您使用Month函数的方式存在问题

您没有为列名设置引号,它应该是:

$test = MyModal::selectRaw('month(date_col) as temp')->get();

它应该工作


推荐阅读