简体   繁体   中英

Laravel 5.4 updateOrCreate doesnt work

What i have:

Invoice and Invoiceitems models with hasMany and belongsTo Relationship with eachother. Invoice can have many invoice items and one invoice item will belong to its invoice only. Basic one.

Situation: Create works just fine. But when im trying to update an existing invoice with standard createOrUpdate Following happens.

  1. if new row has not been created, it updates the existing invoices just fine.
  2. if I added new invoice items, it gives out Undefined index: id error.

This is how Im using createOrUpdate:

$invoice->update($invoiceRequest->except('items'));

foreach($items as $item) {
        $invoice->invoiceitem()->updateOrCreate(['id'=> $item['id']],$item);
}

What exactly am I missing here?

Below is how my $items looks like

 {
 "id": "1",
 "invoiceable_id": "3",
 "fiscal_id": "2",
 "itemdue": "2018-01-19",
 "description": "a",
 "amount": "1000"
 },
 {
 "id": "2",
 "invoiceable_id": "2",
 "fiscal_id": "2",
 "itemdue": "2018-01-20",
 "description": "b",
 "amount": "1000"
 },
 {
 "id": "3",
 "invoiceable_id": "3",
 "fiscal_id": "2",
 "itemdue": "2018-01-19",
 "description": "c",
 "amount": "1200"
 },
 {
 "invoiceable_id": "1",
 "fiscal_id": "1",
 "itemdue": "2018-01-24",
 "description": "renewals",
 "amount": "100"
 }

Item with ids should be updated and last item(without id)should be created as new row. Someone Please let me know where exactly im missing. If you require more information, please let me know

The last element in the $items doesn't have id :

{
    "invoiceable_id": "1",
    "fiscal_id": "1",
    "itemdue": "2018-01-24",
    "description": "renewals",
    "amount": "100"
}

That's why $item['id'] gives you the error.

You may want to check the data with something like this:

if (isset($item['id']))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM