dimanche 7 octobre 2018

laravel update Has Many Relation for items in invoice

I'm trying to update items in the invoice, and I need and the problem when deleting item or add an item if I delete all item it updates I need help, please

invoice table

  • id
  • invoice _no
  • date
  • sub_total
  • discount
  • total

items table

  • id

  • item_code

  • item_desc

  • unit_price

invoice_items table

  • invoice_id

  • item_id

  • unit_price

  • qty

invoice model

public function items()
    {
        return $this->hasMany(InvoiceProduct::class, 'invoice_id');
    }

my controller update

$invoice = Invoice::findOrFail($id);

        $items = [];
        $itemIds = [];
        $subTotal = 0;

        foreach($request->items as $item) {
            if(isset($item['id'])) {
                InvoiceProduct::where('invoice_id', $invoice->id)
                    ->Where('id', $item['id'])
                    ->update($item);

                $itemIds[] = $item['id'];
               $item ='please re add items';
            } else {
                $items[] = new InvoiceProduct($item);
            }

            $subTotal += $item['unit_price'] * $item['qty'];
        }


        $data = $request->except('items');
        $data['sub_total'] = $subTotal;
        $data['total'] = $data['sub_total'] - $request->discount;

        $invoice->update($data);

        InvoiceProduct::whereNotIn('id', $itemIds)
            ->where('invoice_id', $invoice->id)
            ->delete();

        if(count($items)) {
            $invoice->items()->saveMany($items);
        }
 return response()
            ->json(['saved' => true, 'id' => $invoice->id]);
    }



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire