Laravel发票和InvoiceItems-如何更新?

时间:2018-12-05 13:04:09

标签: javascript laravel vue.js vuejs2 laravel-5.7

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

我有两个表TicketInvoiceTicketInvoiceItems,其关系类似TicketInvoice hasMany TicketInvoiceItemsTicketInvoiceItems属于TicketInvoice ...

我可以成功创建TicketInvoiceTicketInvoiceItems但我不知道如何更新...

这是我的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);

    }

1 个答案:

答案 0 :(得分:0)

首先,删除子记录:

    $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);