[英]Not able to update a field using Foreach in Laravel
我有以下數組:
var_dump($steps_filt);
Output:
array(2) { [0]=> string(15) "Text1" [1]=> string(23) "Text2" }
以及以下 object:
var_dump($step_ids);
object(Illuminate\Support\Collection)#400 (1) { ["items":protected]=> array(2) { [0]=> int(2339) [1]=> int(2340) } }
我正在嘗試使用下面的 $steps_filt 值更新 $step_ids 字段,但我確定有問題,因為 output 不正確:
foreach($step_ids as $index => $steps_filt){
DB::table('steps')->where('id', $step_ids)->update(['step' => $steps_filt]);
}
你檢查錯誤日志了嗎? 它可能會告訴您可能出了什么問題。
但這里有一個可能的問題: $step_ids
變量是一個 Laravel 集合。 您正在遍歷集合中的項目,但DB::table('steps')->where()
調用引用的是集合而不是當前項目 ID(您已將其命名為$steps_filt
)。
我認為您可能誤解了foreach
循環在 PHP 中的工作原理。 例如,在循環的第一次迭代中, $index
將為 0, $steps_filt
將為 2339。
做你想做的一個天真的解決方案可能是這樣的:
$step_ids_array = $step_ids->toArray(); // Easier to work with if both are array (or collection)
for ($i = 0; $i < count($step_ids_array); ++$i) {
$step_id = $step_ids_array[$i];
$step_text = $steps_filt[$i];
DB::table('steps')->where('id', $step_id)->update(['step' => $step_text]);
}
更新:也許像這樣解決它更清潔:
$combined = $step_ids->combine($steps_filt);
// $combined will now be a collection where the keys are the IDs and the values are the texts
foreach ($combined as $step_id => $step_text) {
DB::table('steps')->where('id', $step_id)->update(['step' => $step_text]);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.