laravel 查询生成器如何仅从 dateTime 字段中检索年份和月份
laravel query builder how to only retrieve year and month from dateTime field
我只想 select 从数据库中的 dateTime 字段获取月份和年份我试过这个
$historyMonth = App\Models\HistoryCostEstimation::where('user_id',$id)->orderBy('created_at','desc')->toDateString('Y-m')->get();
但它不起作用有什么建议吗?
因为您总是想要那种格式,所以您可以在 HistoryCostEstimation
模型中定义一个 Accessor
,如下所示:
public function getCreatedAtAttribute($date) {
return Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('Y-m');
}
并且您可以在不进行任何转换的情况下查询记录:
App\Models\HistoryCostEstimation::where('user_id',$id)
->orderBy('created_at','desc')
->get();
我只想 select 从数据库中的 dateTime 字段获取月份和年份我试过这个
$historyMonth = App\Models\HistoryCostEstimation::where('user_id',$id)->orderBy('created_at','desc')->toDateString('Y-m')->get();
但它不起作用有什么建议吗?
因为您总是想要那种格式,所以您可以在 HistoryCostEstimation
模型中定义一个 Accessor
,如下所示:
public function getCreatedAtAttribute($date) {
return Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('Y-m');
}
并且您可以在不进行任何转换的情况下查询记录:
App\Models\HistoryCostEstimation::where('user_id',$id)
->orderBy('created_at','desc')
->get();