在Laravel PHP中使用foreach更新字段
我正试图根据其唯一字段在Laravel PHP中使用foreach更新字段,php,ajax,laravel,Php,Ajax,Laravel,我正试图根据其唯一字段taskCode 并将从tbl_projtask 我有这个2变量 $request->dataWeight 此变量来自ajax请求,该请求包含类似于95,75,65的值,该值由逗号分隔 $request->dataweighattr 此变量来自ajax请求,该请求包含如下内容TaskCode1、TaskCode2、TaskCode3 在myMainController.php中 我有这个密码 $myString = $request->dataWeightAt
taskCode
并将从tbl_projtask
我有这个2变量
$request->dataWeight
此变量来自ajax请求,该请求包含类似于95,75,65
的值,该值由逗号分隔$request->dataweighattr
此变量来自ajax请求,该请求包含如下内容TaskCode1、TaskCode2、TaskCode3
MainController.php中
我有这个密码
$myString = $request->dataWeightAttr;
foreach($myString as $value){
DB::table('tbl_projtask')
->where('taskCode', $value)
->update([
'taskWeight'=> $request->dataWeight,
'by_id'=> auth()->user()->id,
'updated_by'=> auth()->user()->name,
'updated_at' => now()
]);
}
正如您在我的update
code中看到的那样
我使用request->dataweighattr
查找应该更新哪些行,并使用$request->dataWeight
特定taskCode
我这样做对吗?如果要更新相同的字段但不同的id,可以使用where而不是foreach
DB::table('tbl_projtask')
->whereIn('taskCode', $request->dataWeightAttr)
->update([
'taskWeight'=> $request->dataWeight,
'by_id'=> auth()->user()->id,
'updated_by'=> auth()->user()->name,
'updated_at' => now()
]);
如果要更新相同的字段但不同的id,可以使用where而不是foreach
DB::table('tbl_projtask')
->whereIn('taskCode', $request->dataWeightAttr)
->update([
'taskWeight'=> $request->dataWeight,
'by_id'=> auth()->user()->id,
'updated_by'=> auth()->user()->name,
'updated_at' => now()
]);
将字符串转换为数组
$dataWeight = explode(',',$request->dataWeight); // convert to array
$dataWeightAttr = explode(',',$request->dataWeightAttr); // convert to array
假设两个数组中都有相关值
foreach($dataWeightAttr as $key => $value){
DB::table('tbl_projtask')
->where('taskCode', $value)
->update([
'taskWeight'=> $dataWeight[$key],
'by_id'=> auth()->user()->id,
'updated_by'=> auth()->user()->name,
'updated_at' => now()
]);
}
将字符串转换为数组
$dataWeight = explode(',',$request->dataWeight); // convert to array
$dataWeightAttr = explode(',',$request->dataWeightAttr); // convert to array
假设两个数组中都有相关值
foreach($dataWeightAttr as $key => $value){
DB::table('tbl_projtask')
->where('taskCode', $value)
->update([
'taskWeight'=> $dataWeight[$key],
'by_id'=> auth()->user()->id,
'updated_by'=> auth()->user()->name,
'updated_at' => now()
]);
}
是否要更新与taskCode相关的taskWeight?是的,我要更新taskWeight,其中taskCode是从$request->dataWeightAttr
中给定的。是否要更新与taskCode相关的taskWeight?是的,我要更新taskWeight,其中taskCode是从$request->dataWeightAttr
中给定的