Laravel - 仅从数据库中的日期获取年份
Laravel - Take only Year from Date in Database
我在约会时遇到问题,只能得到日期的年份。我的日期显示并存储在我的数据库中:2014-09-07
。我只想取那个日期的年份(即 2014 年)。
这是我从数据库中获取日期的代码:
$year = DB::table('pets')->pluck('dates')->unique();
这会从 dates
列中挑选出每个唯一的日期。这非常有效,并且可以毫无问题地显示完整日期。
到目前为止我已经试过了:我设法只使用 selectRaw('substr(dates,1,4) as year')
得到了年份。结果是:{"year":"2014"}
。我无法摆脱括号并假设它的格式错误?
基本上,我需要帮助才能从 mySQL 数据库中的日期获取年份。
我认为你在使用selectRaw()
时使用get()
然后编码json。所以它包括字段名称。如果你得到列,你应该使用 pluck()
或者如果你得到一个值,你应该使用 value()
.
$year = DB::table('pets')->selectRaw('substr(dates,1,4) as dates')->pluck('dates')->unique();
或在blade
@php( $year =( json_decode($year, true) )['year'] )
这可能晚了,但出于学习目的:
使用模型方法你可以做到这一点。
Pets::pluck('dates')->map(function ($pet) {
return $pet->format('Y');
})->unique();
我在约会时遇到问题,只能得到日期的年份。我的日期显示并存储在我的数据库中:2014-09-07
。我只想取那个日期的年份(即 2014 年)。
这是我从数据库中获取日期的代码:
$year = DB::table('pets')->pluck('dates')->unique();
这会从 dates
列中挑选出每个唯一的日期。这非常有效,并且可以毫无问题地显示完整日期。
到目前为止我已经试过了:我设法只使用 selectRaw('substr(dates,1,4) as year')
得到了年份。结果是:{"year":"2014"}
。我无法摆脱括号并假设它的格式错误?
基本上,我需要帮助才能从 mySQL 数据库中的日期获取年份。
我认为你在使用selectRaw()
时使用get()
然后编码json。所以它包括字段名称。如果你得到列,你应该使用 pluck()
或者如果你得到一个值,你应该使用 value()
.
$year = DB::table('pets')->selectRaw('substr(dates,1,4) as dates')->pluck('dates')->unique();
或在blade
@php( $year =( json_decode($year, true) )['year'] )
这可能晚了,但出于学习目的: 使用模型方法你可以做到这一点。
Pets::pluck('dates')->map(function ($pet) {
return $pet->format('Y');
})->unique();