Laravel 8 - 仅保存 foreach 循环中的最后一条记录

Laravel 8 - just save only last record in foreach loop

在 Controller 中,我想保存数据,但是当我尝试使用 foreach 循环时,它只保存了最后的记录

foreach (Form_821_item::group_items as $item) {
        foreach ($item['code'] as $code) { 
                $items = IntersectingList::where('trial_id', $form_821->trial_balance_id)->where('account_code', 'like', $code . '%')->get();
                if ($items) {
                    foreach ($items as $item) {
                        $account_name = $item->account_name;
                        $account_code = $item->account_code;
                        if ($item->total_balance_debit != 0) {
                            $financial_statements = $item->total_balance_debit;
                            $total_cash += $item->total_balance_debit;
                        } else {
                            $financial_statements = $item->total_balance_credit;
                            $total_cash += $item->total_balance_credit;
                        }
                    }
                }
            }
        $data = new Form_821_item();
        $data->form_821_id = $form_821->id;
        $data->account_name = $account_name;
        $data->account_code = $account_code;
        $data->financial_statement = $financial_statements;
        $data->save();
    }

还有什么建议吗?

您需要将插入代码放入 foreach

foreach (Form_821_item::group_items as $item) {
    foreach ($item['code'] as $code) { 
            $items = IntersectingList::where('trial_id', $form_821->trial_balance_id)->where('account_code', 'like', $code . '%')->get();
            if ($items) {
                foreach ($items as $item) {
                    $account_name = $item->account_name;
                    $account_code = $item->account_code;
                    if ($item->total_balance_debit != 0) {
                        $financial_statements = $item->total_balance_debit;
                        $total_cash += $item->total_balance_debit;
                    } else {
                        $financial_statements = $item->total_balance_credit;
                        $total_cash += $item->total_balance_credit;
                    }
                    $data = new Form_821_item();
                    $data->form_821_id = $form_821->id;
                    $data->account_name = $account_name;
                    $data->account_code = $account_code;
                    $data->financial_statement = $financial_statements;
                    $data->save();
                }
            }
        }
    
}