Laravel Eloquent Pluck产生了不正确的数据 [英] Laravel Eloquent Pluck produced incorrect data

查看:23
本文介绍了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;
}

这篇关于Laravel Eloquent Pluck产生了不正确的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆