简体   繁体   English

Laravel 5.4 updateOrCreate不起作用

[英]Laravel 5.4 updateOrCreate doesnt work

What i have: 我有的:

Invoice and Invoiceitems models with hasMany and belongsTo Relationship with eachother. InvoiceInvoiceitems模型与hasManybelongsTo相互关系。 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. 但是,当我尝试使用标准createOrUpdate更新现有发票时,会发生以下情况。

  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. 如果我添加了新的发票项目,它会给出未定义的索引:id错误。

This is how Im using createOrUpdate: 这就是我使用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. 应更新具有ID的项目,并将最后一项(无id)创建为新行。 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 : $items中的最后一个元素没有id

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

That's why $item['id'] gives you the error. 这就是$item['id']给你错误的原因。

You may want to check the data with something like this: 您可能想要使用以下内容检查数据:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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