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

更新数据库中的复选框值

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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?