Laravel Eloquent Pluck产生了不正确的数据

问题描述:

试图通过采摘获得创建日期.

Trying to get created_at date using pluck.

        $campaigns_dates = CampaignHistory::where('status', "Complete")->orderBy( 'created_at', 'ASC' )->pluck('created_at');
        $campaigns_dates = json_decode( $campaigns_dates );
        return $campaigns_dates;

//获取此信息

["2020-06-29T14:19:03.000000Z","2020-06-29T14:19:42.000000Z","2020-07-29T14:23:54.000000Z","2020-08-28T14:55:53.000000Z","2020-08-29T14:17:40.000000Z","2020-09-29T14:18:27.000000Z","2020-09-29T14:21:13.000000Z"]

//但是想要这个

Example: ["2020-06-29 14:19:03","2020-06-29 14:19:42"]

您可以使用map操作将日期重新格式化为给定格式:

You can use the map operation to reformat your date as your given format :

public function index() {
 
    $campaigns_dates = CampaignHistory::orderBy('created_at', 'ASC')
        ->pluck('created_at')
        ->map
        ->format('Y-m-d H:i:s');

    $campaigns_dates = json_decode($campaigns_dates);
    return $campaigns_dates;
}

替代解决方案:由于

Alternative Solution : There is an alternative solution with selectRaw() method, thanks to @OMR for provide this solution :

public function index() {
 
    $campaigns_dates = CampaignHistory::orderBy('created_at', 'ASC')
        ->selectRaw("DATE_FORMAT(created_at, '%Y-%m-%d %H:%i:%s') as formatted_date")
        ->pluck('formatted_date');

    $campaigns_dates = json_decode($campaigns_dates);
    return $campaigns_dates;
}