更新数据库中的复选框值

更新复选框形式发送的记录的最佳方法是什么。如何知道哪一个未被选中。


我的算法未设置所有值,然后再次检查并从请求中检查ID。此外,由于所有值每一次都会更新,因此会引起时间戳问题。


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();

    }

我想执行更好的解决方案,其中仅在表单中更改的值在后端被“触摸”。


qq_遁去的一_1
浏览 155回答 1
1回答

梵蒂冈之花

像这样创建它,不要忘记$id用实际的ID替换:<input type="hidden" name="default_plans[$id]" value="0" /><input type="checkbox" name="default_plains[$id]" value="1" />然后在您的php代码中遍历模型并在事务中更新它们。public function plansUpdate(Request $requets) {&nbsp; &nbsp; $plans = $this->planService->getAllPlans();&nbsp; &nbsp; $defaultPlans = $request->get('default_plans');&nbsp; &nbsp; DB::beginTransaction();&nbsp; &nbsp; foreach($plans as $plan) {&nbsp; &nbsp; &nbsp; &nbsp; $plan->is_default = boolval($defaultPlans[$plan->id] ?? false);&nbsp; &nbsp; &nbsp; &nbsp; $plan->save();&nbsp; &nbsp; }&nbsp; &nbsp; DB::commit();&nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP