【发布时间】:2015-11-05 12:04:47
【问题描述】:
我正在使用 postgres 制作我的第一个 laravel 项目,我希望能够访问本月所有生日的人(我的人员表有一个生日字段,即日期)。我可以使用 extract 从数据库中获取这些记录,如下所示:
select * from people
where extract (month from birthdate) = 11;
但是当我在控制器中尝试几种不同的方法时,我会收到“未知列”错误:
$birthday_people = DB::table('people')
->where ("extract(month from birthdate)", "=", "11")
->get();
(我最终会调整它以与 Carbon::now()->month 进行比较,并使用模型 Person::all(),但直到我会得到一些结果,我会尽可能简单)
有没有一种特殊的方法可以从 laravel 中的日期获取月份?
更新:我现在在我的 Person 模型中使用范围。当我给它一个确切的日期时,我可以得到人的结果:
public function scopeBirthdays($query)
{
return $query->where('birthdate', '=', '1947-11-02');
}
如果我这样做,我可以在一个月内获得结果,但问题是它似乎不再知道它是 People 的集合(我无法访问人员列当我显示它并且我无法链接其他范围时):
public function scopeBirthdays($query)
{
return $query->whereRaw('extract(month from birthdate) = ?', ['11'])->get();
}
Laravel 的查询构建器提供 'whereMonth'-(似乎是最正确的),但它给了我一个“未定义的函数”错误,直到我把 bool 放在最后,现在当前的错误提示它解释的是几个月而不是哪个(?):
public function scopeBirthdays($query)
{
return $query->whereMonth('birthdate', '=', Carbon::today()->month, true);
}
我得到: 语法错误:7 错误:“月”或附近的语法错误 LINE 1: select * from "people" where 1 month("birthdate") = $1 ^ (SQL: select * from "people" where 1 month("birthdate") = 11)
最终更新:通过在我的范围内使用 whereRaw,我能够返回结果(被正确解释为人):
public function scopeBirthdays($query)
{
return $query->whereRaw('extract(month from birthdate) = ?', [Carbon::today()->month])->orderBy ('birthdate', 'asc');
}
谢谢大家!
【问题讨论】:
标签: postgresql laravel extract