douwei1904 2019-04-28 21:20
浏览 82
已采纳

更新数据库中的复选框值

What is the best way to update records send from checkbox form. How to get to known which one have been unchecked.

My algorithm unset all values than goes again and check ids from request. Moreover it cause problem with timestamps, because all values are being updated every single time.

public function plansUpdate(Request $request){
        //set all plans as not default to handle unchecked
        $plans = $this->planService->getAllPlans()->pluck('id');
        PlanModel::whereIn('id', $plans)->update(['is_default' => false]);

        //set checked plans as default
        $defaultPlans = $request->get('default-plans');
        PlanModel::whereIn('id', $defaultPlans)->update(['is_default' => true]);

        return redirect()->back();
    }

I would like to perform better solution where only values changed in the form are being "touch" in the back-end.

  • 写回答

1条回答 默认 最新

  • duanji9481 2019-04-28 21:36
    关注

    Create it like this, don't forget to replace $id with the actual ID:

    <input type="hidden" name="default_plans[$id]" value="0" />
    <input type="checkbox" name="default_plains[$id]" value="1" />
    

    Then in your php code iterate over the models and update them in transaction.

    public function plansUpdate(Request $requets) {
        $plans = $this->planService->getAllPlans();
    
        $defaultPlans = $request->get('default_plans');
        DB::beginTransaction();
        foreach($plans as $plan) {
            $plan->is_default = boolval($defaultPlans[$plan->id] ?? false);
            $plan->save();
        }
        DB::commit(); 
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算