如果语句改进版本

Fre*_*man 1 php laravel

有什么方法可以改进这些代码行。我是指编写代码的缩短方法吗?我正在开发 Laravel 8..

if ($request->logo) {
       $setting->updateOrCreate(['key' => 'logo'], ['value' => $request->logo]);
   }
    
if ($request->footerLogo) {
       $setting->updateOrCreate(['key' => 'footerLogo'], ['value' => $request->footerLogo]);
}
if ($request->favicon) {
    $setting->updateOrCreate(['key' => 'favicon'], ['value' => $request->favicon]);
 }
Run Code Online (Sandbox Code Playgroud)

Joh*_*obo 6

你可以这样做。将密钥保存在数组中。然后内部循环检查请求有键。如果它有键,则更新行

  $settingKey=["logo","footerLogo","favicon"];

    foreach ($settingKey as $key){
        if($request->has($key)){
            $setting->updateOrCreate(['key' =>$key], ['value' => $request->{$key}]);
        }
    }
Run Code Online (Sandbox Code Playgroud)

您也可以这样做来设置密钥而不是硬编码。但请注意,如果它的新键那么它可能不存在于 db 表中。

$settingKey=Setting::pluck('key')->toArray();
Run Code Online (Sandbox Code Playgroud)

灵感来自@N69S 答案

$upserts = [];
    foreach ($settingKey as $key){
        if($request->has($key)){
            $upserts[]= ['key' => $key, 'value' => $request->{$key}];

        }
    }

    if(count($upserts)){
        $setting->upsert($upserts, ['key'], ['value']);
    }
Run Code Online (Sandbox Code Playgroud)