Laravel 发票和发票项目 - 如何更新?

Laravel Invoice & InvoiceItems - How to Update?

我正在使用 Laravel 5.7 & VueJs 2.5.* ...

我有两个 table TicketInvoice & TicketInvoiceItems,它们之间的关系是 TicketInvoice hasMany TicketInvoiceItems & TicketInvoiceItems belongsTo TicketInvoice...

我可以成功创建TicketInvoice & TicketInvoiceItems, 但我不知道如何更新...

这是我的 store 方法(有效):

    public function store(Request $request)
    {   
        $ticketInvoiceItems = collect();

        foreach($request['ticketInvoiceItems'] as $invoiceItem) {
        $ticketInvoiceItems->push(new TicketInvoiceItems ([
            'passenger_name' => $invoiceItem ['passenger_name'],
            'ticket_no' => $invoiceItem ['ticket_no'],
            'fares' => $invoiceItem ['fares'],
            'sub_total' => $invoiceItem ['sub_total']
        ]));
        }

        $ticketInvoice = TicketInvoice::create([
            'vendor_id' => $request['vendor_id'],
            'ticket_invoice_no' => $request['ticket_invoice_no'],
            'ticket_invoice_date' => $request['ticket_invoice_date'],
            'ticket_invoice_fares_total' => $request['ticket_invoice_fares_total'],
            'ticket_invoice_grand_total' => $request['ticket_invoice_grand_total'],
        ]);

        $ticketInvoice->ticketInvoiceItems()->saveMany($ticketInvoiceItems);
    }

这是我的 update 方法(无效 :'( ):

    public function update(Request $request, $id)
    {
        $ticketInvoice = TicketInvoice::findOrFail($id);

        $ticketInvoiceItems = collect();

        foreach($request['ticketInvoiceItems'] as $invoiceItem) {
            $ticketInvoiceItems->push(new TicketInvoiceItems ([
                'passenger_name' => $invoiceItem ['passenger_name'],
                'ticket_no' => $invoiceItem ['ticket_no'],
                'fares' => $invoiceItem ['fares'],
                'sub_total' => $invoiceItem ['sub_total']
            ]));
            }
            $ticketInvoice->update($request->all());
            $ticketInvoice->ticketInvoiceItems()->update($ticketInvoiceItems);

    }

首先,删除子记录:

    $ticketInvoice->ticketInvoiceItems()->delete();

然后存储新的:

    $ticketInvoiceItems = collect();

    foreach($request['ticketInvoiceItems'] as $invoiceItem) {
        $ticketInvoiceItems->push(new TicketInvoiceItems ([
            'passenger_name' => $invoiceItem ['passenger_name'],
            'ticket_no' => $invoiceItem ['ticket_no'],
            'fares' => $invoiceItem ['fares'],
            'sub_total' => $invoiceItem ['sub_total']
        ]));
    }

    $ticketInvoice->ticketInvoiceItems()->saveMany($ticketInvoiceItems);