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 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考