samedi 8 juin 2019

Inserting if record not exist, updating if exist

Hiii I have 2 database tables with the columns table :1 "id, invoice_id, subject, total" table:2 "id, invoice_id, item_name, price".whenever i try to update record with the help of invoice_id if record doesn't exist in item table it will not insert new item in item table.

here i attached my JSON data

{ 
"date": "2019-06-08", 
"client_id": "1", 
"currency_id": 4, 
"total_amount": null, 
"subject": "RD Management", 
"items": [
{ 
"item_name": "Saving",
"price": "500"
}, 
{ 
"item_name": "Fix",  
"price": "500"
},
{ 
item_name": "Current", 
"price": "200"
} 
]
}

here one problem is also my JSON can not send item_id also so without item id how can i update my record...??? here 3rd item is not present in my table

here is my controller

foreach ($request->items as $key => $items) 
{
$item_update = [
'item_name'    => $items['item_name'],
'price'  => $items['price']
];
DB::table('items')
->where('invoice_id', $id)
->update($item_update);
}

I Except output like this

"items": [
{
"id": 1,
"invoice_id": "1",
"item_name": "Saving",
"price": "500",    
},
{
"id": 2,
"invoice_id": "1",
"item_name": "Fix",
"price": "500",      
},
{
"id": 3,
"invoice_id": "1",
"item_name": "current",
"price": "200",       
},
]

but my actual output is

"items":[
{
"id":"1"
"item_name": "Fix",
"price": "500",       
},
{
"id":"2"
"invoice_id": "1",
"item_name": "Fix",
"price": "500",       
}
]



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2Z8uKlk
via IFTTT

Aucun commentaire:

Enregistrer un commentaire