试图从 laravel 中的日期获取月份(并且 postgres 提取不工作)

Trying to get month from date in laravel (and postgres extract not working)

我正在做我的第一个 laravel 项目,使用 postgres,我希望能够访问这个月生日的所有人(我的人 table 有一个生日日期字段)。我可以使用 extract 从数据库中获取这些记录,如下所示:

select * from people 
   where extract (month from birthdate) = 11;

但是当我在我的控制器中尝试几种不同的方式时,我得到 'unknown column' 错误:

$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');
}

如果我这样做,我 可以 得到一个月的结果,但要注意的是它似乎不再知道它是一个人的集合(我可以当我显示它时无法访问人员列并且我无法链接其他范围):

public function scopeBirthdays($query)
{
    return $query->whereRaw('extract(month from birthdate) = ?', ['11'])->get();
}

Laravel 的查询构建器提供了 'whereMonth'-(似乎最 正确 ),但它给了我一个 'undefined function' 错误,直到我把 bool 放在最后,现在当前的错误表明它正在解释月数而不是月数(?):

public function scopeBirthdays($query)
{
   return $query->whereMonth('birthdate', '=', Carbon::today()->month, true);
}

我得到: 语法错误:7 错误:"month" 处或附近的语法错误 第 1 行:select * 来自 "people",其中 1 个月("birthdate")= $1 ^ (SQL: select * 来自 "people" 其中 1 个月("birthdate") = 11)

最终更新: 通过在我的范围内使用 whereRaw,我能够返回结果(被正确解释为人):

public function scopeBirthdays($query)
{
    return $query->whereRaw('extract(month from birthdate) = ?', [Carbon::today()->month])->orderBy ('birthdate', 'asc');
}

谢谢大家!

根据上一个问题尝试:

$birthday_people = DB::table('people')
    ->whereRaw("extract(month from birthdate)", "=", "11")
    ->get();

可以设置is as关系

public function custom(){
   return $this->hasMany('App\Models\People')->whereRaw("extract(month from birthdate)", "=", "11");
}

你可以尝试这样的事情。它将 return 作为 App\People 的实例,因此您仍然可以使用 eloquent 函数。

public function scopeBirthdays($query)
{
    return $query->where('birthdate', 'LIKE', Carbon::today()->year . '-'.Carbon::today()->month.'%');
}

我对 Carbon 没有太多经验,我假设 Carbon::today() 将 return 一个带有年月日的对象。