为什么写入json字段的日期时间有无效值?

问题描述 投票:0回答:1

在 laravel 10 应用程序中,我需要将登录用户的 json 字段信息和登录时间写入

我用代码来做:

\Log::info(varDump($timezone, ' -1 $timezone::'));
\Log::info(varDump(Carbon::now($timezone), ' -1 BEFORE EXIT Carbon::now($timezone)::'));
return KeyData::create([
    'key' => $key,
    'data' => [["user_id" => $loggedUserId, "online_from" => Carbon::now($timezone), 'temp_field' => 'temp_value']],
    'expired_at' => Carbon::now($timezone)->addSeconds($cachingTimeInSeconds)
]);

检查日志输出,我在带有时区的日期字段中看到有效的时区和时间。

-1 $timezone:: : Europe/Kiev
[2024-05-23 10:03:10] local.INFO:  (Object of Carbon\Carbon) : -1 BEFORE EXIT Carbon::now($timezone):: : Array
(
    [ * endOfTime] =>
    [ * startOfTime] =>
    [ * constructedObjectId] => 000000000000055b0000000000000000
    [ * localMonthsOverflow] =>
    [ * localYearsOverflow] =>
    [ * localStrictModeEnabled] =>
    [ * localHumanDiffOptions] =>
    [ * localToStringFormat] =>
    [ * localSerializer] =>
    [ * localMacros] =>
    [ * localGenericMacros] =>
    [ * localFormatFunction] =>
    [ * localTranslator] =>
    [ * dumpProperties] => Array
        (
            [0] => date
            [1] => timezone_type
            [2] => timezone
        )

    [ * dumpLocale] =>
    [ * dumpDateProperties] =>
    [date] => 2024-05-23 10:03:10.253696
    [timezone_type] => 3
    [timezone] => Europe/Kiev
)

但是检查数据我发现“online_from”中的值无效:

enter image description here

表是通过迁移创建的:

    Schema::create('key_data', function (Blueprint $table) {
        $table->id();
        $table->string('key', 255);
        $table->json('data')->nullable();
        $table->dateTime('expired_at');
        $table->timestamp('created_at')->useCurrent();

        $table->index(['key', 'expired_at'], 'key_data_key_expired_at_index');
    });

检查整理我看到:

CREATE TABLE `key_data` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`key` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`data` json DEFAULT NULL,
`expired_at` datetime NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `key_data_key_expired_at_index` (`key`,`expired_at`)
) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

出了什么问题以及如何解决?

mysql laravel mysql-json
1个回答
0
投票

在将日期时间插入 JSON 之前,请确保日期时间格式正确(例如 ISO 8601)。我认为您会看到不同的结果,因为您的记录器可能会将日期时间转换为更易读的格式。 $now = Carbon::now($timezone)->toIso8601String(); $expiry = Carbon::now($timezone)->addSeconds($cachingTimeInSeconds)->toIso8601String(); return KeyData::create([ 'key' => $key, 'data' => [["user_id" => $loggedUserId, "online_from" => $now, 'temp_field' => 'temp_value']], 'expired_at' => $expiry ]);

© www.soinside.com 2019 - 2024. All rights reserved.