这是示例查询。
$test = DB::table('tesing')
->where('id', $id)
->update(['a' => $a,'b'=>$b,'c'=>$c,'d'=>$d']);
E.g。当用户允许选择是否只想更新'a'值或'b'值等等。如何确保仅更新用户选择的字段。将有一个允许用户选择要更新的字段的复选框。之后,只会更新用户选中的特定字段。
$test = DB::table('tesing')
->where('id', $id)
->update(['a' => $a']);
当用户选择“a”字段时,只会更新“a”字段。 而不是使用if-else语句,我可以使用其他什么方式?
答案 0 :(得分:0)
假设a
b
c
是列名,请尝试使用Eloquent:
public function name($id, Request $request)
{
$test = App\Test::find($id);
foreach ($request->all() as $key => $value) {
$test->{$key} = $value;
}
$test->save();
}
答案 1 :(得分:0)
最简单的方法是创建一个您正在使用的特定复选框名称数组,以便用户选择要更新的字段。将选择复选框命名为与可更新列对应,然后仅根据复选框选择器进行更新,以及用户希望从收到的$ request对象更新的那些。
类似于柱子的peudo代码(以及相应命名的表单字段)“A”,“B”,“C”:
public function update(Request $request, $routeModelBoundObjectToUpdate){
$userCheckboxNames = ['ckA', 'ckB', 'ckC'];
$updates = [];
foreach ($request->all() as $key => $value) {
if(in_array($key, $userCheckBoxNames) && $value == 'on')
$updates[] = [substr($key, 2) => $request->get(substr($key, 2));
}
$routeModelBoundObjectToUpdate->update($updates);
}
希望这有帮助。