gpt4 book ai didi

Laravel:JSON 响应中日期的意外行为

转载 作者:行者123 更新时间:2023-12-04 19:03:25 25 4
gpt4 key购买 nike

我正在 Laravel 中创建一个返回 JSON 的 Web 服务。

我创建了一个 Account模型如下:

class Account extends Eloquent {

// The database table used by the model.
// (If not defined then lowercase and plural of class name is consider as a table name)
protected $table = "account";

// define which column can be mass assign
protected $fillable = array("user_id", "account_group_id", "generated_by", "image", "name",
"address", "zip", "area_id", "mobile", "email", "phone", "fax",
"website", "pan", "cst", "tin", "ecc", "iesc", "transport",
"other", "outstanding", "cform", "status", "mitp");

// To prevent column from mass assignment.
protected $guarded = array('id');

// Change Variable for CREATED_AT and UPDATED_AT
const CREATED_AT = 'itp';
const UPDATED_AT = 'utp';
}

我正在从 Account 获取字段使用 user_id并通过 Response::json() 返回 JSON在我的 Controller 中
$accountData = Account::select('name', 'status', 'id', 'user_id', 'utp')->where('user_id', Auth::id())->first();
$return = array(
'result' => 'success',
'msg' => 'Login Successfully.',
'data' => $accountData
);
return Response::json($return);

在此, utp行为符合预期并以字符串形式返回日期:
{
"result": "success",
"msg": "Login Successfully.",
"data": {
"name": "Demo",
"status": 0,
"id": 143,
"user_id": 207,
"utp": "2015-07-01 18:38:01"
}
}

但是,如果我像这样将每个值与帐户模型分开:
$return = array(
'result' => 'success',
'msg' => 'Login Successfully.',
'data' => $accountData['user_id'],
'account_id' => $accountData['id'],
'utp' => $accountData['utp'],
'usertype' => 'account',
'status' => $accountData['status']
);

然后这给出了来自 utp 的一些意外行为。
{
"result": "success",
"msg": "Login Successfully.",
"data": 207,
"account_id": 143,
"utp": {
"date": "2015-07-01 18:38:01",
"timezone_type": 3,
"timezone": "Asia\\/Kolkata"
},
"usertype": "account",
"status": 0
}

为什么我的时间戳字段会发生这种情况?

最佳答案

因为 utp Carbon\Carbon 实例。 Model::toJson (实际上 Model::toArray ,但两者都使用)通常处理,并将日期序列化为通常的 ISO3601 格式

对于预期的行为,您需要格式化 Carbon 实例。

"utp" => $accountData['utp']->format("Y-m-d H:i:s"),

或者,将其转换为字符串
"utp" => (string) $accountData['utp'],

关于Laravel:JSON 响应中日期的意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31184170/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com