在 Laravle 6 中,设置 MySQL 字段类型 json 值的重构(基于辅助函数 Arr 实现)
1、现有的代码实现
if ($themeInstallationTask->setting_migrations) { $settingMigrations = $themeInstallationTask->setting_migrations; } $settingMigrations[] = [ 'file' => $availableVersion . '/' . $this->migrateSettingsDataFile, 'exec_at' => now()->utc()->toDateTimeString() ]; $themeInstallationTask->setting_migrations = $settingMigrations; $themeInstallationTask->save();
2、最终生成的结构如下所示,是一个数组,字段名称为:setting_migrations
[ { "file": "v2.0.15-rc.6/migrate_settings_data.php", "exec_at": "2022-10-31 09:45:06" }, { "file": "v2.0.15-rc.7/migrate_settings_data.php", "exec_at": "2022-10-31 09:45:06" }, { "file": "v2.0.15/migrate_settings_data.php", "exec_at": "2022-10-31 09:45:06" }, { "file": "v2.0.17-rc.0/migrate_settings_data.php", "exec_at": "2022-10-31 09:45:06" } ]
3、决定调整字段的名称为 extra,将 setting_migrations 字段的值纳入其中,代码调整如下,基于辅助函数 Arr 实现。
$extra = $themeInstallationTask->extra; if (Arr::has($extra, 'setting_migrations')) { $settingMigrations = Arr::get($extra, 'setting_migrations'); } $settingMigrations[] = [ 'file' => $file, 'exec_at' => now()->utc()->toDateTimeString() ]; Arr::set($extra, 'setting_migrations', $settingMigrations); $themeInstallationTask->extra = $extra; $themeInstallationTask->save();
4、最终生成的结构如下所示,是一个对象,字段名称为:extra。如图1
{ "setting_migrations": [ { "file": "v2.0.15-rc.6/migrate_settings_data.php", "exec_at": "2022-10-31 09:45:06" }, { "file": "v2.0.15-rc.7/migrate_settings_data.php", "exec_at": "2022-10-31 09:45:06" }, { "file": "v2.0.15/migrate_settings_data.php", "exec_at": "2022-10-31 09:45:06" }, { "file": "v2.0.17-rc.0/migrate_settings_data.php", "exec_at": "2022-10-31 09:45:06" } ] }
近期评论