2015-05-20 161 views
0

我正在尝试构建小API。我正在使用Laravel。如何将时间戳值更新/插入PHP/MySQL中的时间戳字段?

我有这个表,例如:

CREATE TABLE `Incomes` (
    ....................................... 
    `comment` VARCHAR(255) NULL DEFAULT NULL, 
    `dateInsert` TIMESTAMP NULL DEFAULT NULL, 
    `dateUpdate` TIMESTAMP NULL DEFAULT NULL, 
    `dateDelete` TIMESTAMP NULL DEFAULT NULL, 
    PRIMARY KEY (`guid`), 
    ....................................... 
) 
COLLATE='utf8_general_ci' 
ENGINE=InnoDB; 

我做dateUpdate场更新了一些行:

update `Incomes` set `dateInsert` = '1432111937' where `guid` = 'lalvlldlv1laslf' 

之后,我在排这样的数据: enter image description here

我甚至没有时间戳,只有0000-00-00 00:00:00

为什么我会这样?

为什么关于PHP的问题?我正在使用Laravel来更新行。

我有这样的代码,从而产生上述代码:

$jsonArray = $input->data; 
foreach ($jsonArray as $item) { 
    $item = (object)$item; 
    $income = Income::find($item->guid); 
    if($income) { 
     $income->categoryId = $item->categoryId; 
     $income->billId = $item->billId; 
     $income->userId = $item->userId; 
     $income->amount = $item->amount; 
     $income->comment = $item->comment; 
     $income->dateInsert = $item->dateInsert; 
     $income->dateUpdate = $item->dateUpdate; 
     $income->dateDelete = $item->dateDelete; 
     $income->save(); 
    } 
} 

我解析此JSON为$jsonArray变量:行

{ 
    "data": [ 
      { 
       "guid": "lalvlldlv1laslf", 
       "categoryId": "123e1cs", 
       "billId": "12312", 
       "userId": "214123", 
       "amount": 200, 
       "comment": null, 
       "dateInsert": 1432111937, 
       "dateUpdate": null, 
       "dateDelete": null 
      } 
    ] 
} 

为什么我没有得到正常的日期/时间戳记正常?

+0

'TIMESTAMP'列不接受整数来完成,它接受一个格式化字符串,它在内部转换为unix时间戳整数。 –

回答

4

Timestamp数据类型支持格式为Y-m-d H-i-s的日期,因此它的失败,你需要转换成适当的格式。在MySQL中它可以使用from_unixtime

mysql> select from_unixtime('1432111937'); 
+-----------------------------+ 
| from_unixtime('1432111937') | 
+-----------------------------+ 
| 2015-05-20 14:22:17   | 
+-----------------------------+ 
1 row in set (0.05 sec) 

所以更新命令将

update `Incomes` 
set `dateInsert` = from_unixtime('1432111937') 
where `guid` = 'lalvlldlv1laslf' 
+0

好的,所以我的问题应该转换为“如何将时间戳包装到'from_unixtime('...')',对吗? –

+0

这很好,因为许多人可能不知道'from_unixtime'函数或可能'将整数日期值转换为MySQL时间戳值 –