laravel - updateOr创建一行并跳过列更新如果我们得到空值,保留原始值

标签 laravel vue.js laravel-5 eloquent

可以这样做吗?我有一个接受这些参数的函数。

第一次调用时,它将创建由 JSON 文件定义的所有可能的设置并将它们保存到数据库中。这里重要的列是meta,它是字符串列,但保存json值。

一旦数据保存到数据库,元值就不需要再修改,当我们想要保存时,我们也不需要将它们从 UI 发送回服务器。如果 $meta 为空会发生什么?它还会将元列设置为空。如果传入的值为空,是否有一种优雅的方法告诉 laravel 不要更新列,从而保留旧值?

public function saveSetting($section, $parent, $key, $value, $type = 'string', $meta)
{
    if(is_array($value) || is_object($value)) {
        $type = 'json';
        $value = json_encode($value);
    }

    $setting = $this->settings()->updateOrCreate(
        ['theme_id' => $this->id, 'section' => $section, 'key' => $key],
        ['section' => $section, 'parent_id' => $parent, 'key' => $key, 'value' => $value, 'type' => $type, 'meta' => $meta]
    );

    return $setting;
}

现在我想到的唯一解决方案是使用 if 来查看是否设置了元,如下所示:

public function saveSetting($section, $parent, $key, $value, $type = 'string', $meta)
{
    if(is_array($value) || is_object($value)) {
        $type = 'json';
        $value = json_encode($value);
    }

    if(isset($meta)) {
        $setting = $this->settings()->updateOrCreate(
            ['theme_id' => $this->id, 'section' => $section, 'key' => $key],
            ['section' => $section, 'parent_id' => $parent, 'key' => $key, 'value' => $value, 'type' => $type, 'meta' => $meta]
        );
    } else {
        $setting = $this->settings()->updateOrCreate(
            ['theme_id' => $this->id, 'section' => $section, 'key' => $key],
            ['section' => $section, 'parent_id' => $parent, 'key' => $key, 'value' => $value, 'type' => $type]
        );
    }

    return $setting;
}

有没有更好的方法来跳过更新元?

调用 saveSetting 函数的代码如下所示:

            foreach ($section as $key => $setting) {
                $theme->saveSetting($sectionKey, $sectionSetting->id, $key, $setting['value'], $setting['type'], null);
            }

meta 设置为 null,因为我们已经在数据库中拥有了 meta,并且我们的 UI 不需要在用户按下“保存”时将其发送到服务器。我们只向服务器发送用户实际上可以修改的数据。

最佳答案

如果我理解你的问题是正确的......你为什么不想要这样的东西?

$dataToUpdate = [
    'section' => $section,
    'parent_id' => $parent,
    'key' => $key,
    'value' => $value,
    'type' => $type
];

if ($meta) {
    $dataToUpdate['meta'] = $meta;
}

$setting = $this->settings()->updateOrCreate(
    [
        'theme_id' => $this->id,
        'section' => $section,
        'key' => $key
    ],
    $dataToUpdate
);

关于laravel - updateOr创建一行并跳过列更新如果我们得到空值,保留原始值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55733697/

相关文章:

laravel - fatal error : Class 'Collective\Html\HtmlServiceProvider' not found in Laravel when deploying with heroku

php - 如何在laravel php中使用ajax根据日期范围从mysql数据库检索数据?

laravel - 如何在Laravel Rule中传递参数?

vue.js - subview 组件将 prop 传递给 Vue 中的父布局

laravel - 将现有记录附加到 Eloquent hasMany/belongsTo 关系

eloquent - Laravel 5 Eloquent 关系 - 有很多想法

laravel - 如何在 Laravel Voyager 中构建下拉选项的条件列表

javascript - 如何将超链接添加到我的 v-data-table 组件的“应用程序”列?

vue.js - 该值未绑定(bind)在 PrimeVue/TreeSelect 中

php - 辅助函数未加载 laravel 5 - 调用未定义函数