我正在使用Laravel 5.7
和VueJs 2.5.*
...
我有两个表TicketInvoice
和TicketInvoiceItems
,其关系类似TicketInvoice
hasMany TicketInvoiceItems
和TicketInvoiceItems
属于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);
}
答案 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);