Mysql 更新结束时间时,将自动更新字段开始时间
我在我的项目中使用了laravel 6和mysql 5.7,我在模型中放置了两列Mysql 更新结束时间时,将自动更新字段开始时间,mysql,laravel,timestamp,Mysql,Laravel,Timestamp,我在我的项目中使用了laravel 6和mysql 5.7,我在模型中放置了两列start\u time和end\u time,它们都是timestamp类型。在一个操作中,我创建一个记录并初始化start\u time值。在另一个操作中,我更新该记录的end\u time列。 以下是创建项目时的代码: DeviceUsage::create([ 'user_id' => $user->id, 'device_id' => $request->input(
start\u time
和end\u time
,它们都是timestamp
类型。在一个操作中,我创建一个记录并初始化start\u time
值。在另一个操作中,我更新该记录的end\u time
列。以下是创建项目时的代码:
DeviceUsage::create([
'user_id' => $user->id,
'device_id' => $request->input('device_id'),
'start_time' => date('Y-m-d H:i:s'),
]);
这是查询的日志:
'query' => 'insert into `device_usages` (`user_id`, `device_id`, `start_time`, `updated_at`, `created_at`) values (?, ?, ?, ?, ?)',
'bindings' =>
array (
0 => 3,
1 => '1',
2 => '2019-12-11 10:33:51',
3 => '2019-12-11 10:33:51',
4 => '2019-12-11 10:33:51',
),
'time' => 0.68,
create命令后的数据库:
+----+-----------+---------------------+----------+
| id | device_id | start_time | end_time |
+----+-----------+---------------------+----------+
| 1 | 2 | 2019-12-11 11:26:53 | NULL |
+----+-----------+---------------------+----------+
+----+-----------+---------------------+---------------------+
| id | device_id | start_time | end_time |
+----+-----------+---------------------+---------------------+
| 1 | 2 | 2019-12-11 14:59:24 | 2019-12-11 11:29:24 |
+----+-----------+---------------------+---------------------+
这是我的更新代码:
$deviceUsage = DeviceUsage::where('device_id', $oldDeviceId)->where('user_id', $user->id)->whereNull('end_time')->first();
if (!empty($deviceUsage)) {
$deviceUsage->update(['end_time' => date('Y-m-d H:i:s')]);
}
并更新查询日志:
'query' => 'update `device_usages` set `end_time` = ?, `device_usages`.`updated_at` = ? where `id` = ?',
'bindings' =>
array (
0 => '2019-12-11 10:33:51',
1 => '2019-12-11 10:33:51',
2 => 12,
),
'time' => 1.41,
更新命令后的数据库:
+----+-----------+---------------------+----------+
| id | device_id | start_time | end_time |
+----+-----------+---------------------+----------+
| 1 | 2 | 2019-12-11 11:26:53 | NULL |
+----+-----------+---------------------+----------+
+----+-----------+---------------------+---------------------+
| id | device_id | start_time | end_time |
+----+-----------+---------------------+---------------------+
| 1 | 2 | 2019-12-11 14:59:24 | 2019-12-11 11:29:24 |
+----+-----------+---------------------+---------------------+
我不知道为什么
start\u time
会被更新为end\u time
的本地时间(我的本地时间是UTC+3:30)。您是否检查了该字段的默认值?是否设置为“更新时的当前时间戳”是否已选中该字段的默认值?是否设置为“更新时的当前时间戳”哦,是的。但是为什么呢?我的迁移:$table->timestamp('start_time')$表->时间戳('end_time')->nullable()代码>如果将其设置为“currect timestamp on update”,那么无论您是否为其赋值,只要有任何updatethak you@BlackXero,它都将始终设置当前时间戳。写下你的评论作为答案,这样我就可以把它标记为我的答案。谢谢你接受它,我已经把它作为答案写了出来,:)附加文章: