我正在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
$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
}
为什么我的时间戳字段会发生这种情况?
答案 0 :(得分:5)
因为utp
是Carbon\Carbon
个实例。 Model::toJson
(实际为Model::toArray
,但两者都使用了)通常处理,并将日期序列化为通常的ISO3601-ish格式
对于预期的行为,您需要格式化Carbon实例。
"utp" => $accountData['utp']->format("Y-m-d H:i:s"),
或者,将其转换为字符串
"utp" => (string) $accountData['utp'],