【问题标题】:Field start_time is being updated automatically when updating end_time更新 end_time 时,字段 start_time 会自动更新
【发布时间】:2019-12-11 11:35:33
【问题描述】:

我在我的项目中使用 laravel 6 和 mysql 5.7,我在我的模型中放置了两列 start_timeend_time,并且两者都是 timestamp 类型。在一个动作中,我创建了一条记录并初始化 start_time 值。在另一个操作中,我更新了该记录的 end_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,

创建命令后和数据库:

+----+-----------+---------------------+----------+
| id | device_id | start_time          | end_time |
+----+-----------+---------------------+----------+
|  1 |         2 | 2019-12-11 11:26:53 | NULL     |
+----+-----------+---------------------+----------+

这是我的更新代码:

$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 14:59:24 | 2019-12-11 11:29:24 |
+----+-----------+---------------------+---------------------+

我不知道为什么 start_time 会更新为当地时间 end_time(我的当地时间是 UTC+3:30)。

【问题讨论】:

  • 您是否检查了该字段的默认值?是否设置为“当前更新时间戳”
  • 哦,是的。但为什么?我的迁移:$table->timestamp('start_time'); $table->timestamp('end_time')->nullable();
  • 如果它设置为“更新时的当前时间戳”,那么无论您是否为其赋值,只要有任何更新,它都会始终设置当前时间戳
  • 谢谢@BlackXero。将您的评论写为答案,以便我将其标记为我的答案。
  • 谢谢你的接受,我已经把它写成了答案,:)

标签: mysql laravel timestamp


【解决方案1】:

您是否检查了该字段的默认值?是否设置为“当前更新时间戳”

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2012-08-06
  • 1970-01-01
  • 2011-07-16
  • 2016-03-27
  • 2012-03-09
  • 2012-11-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多