Search code examples
laravel-4eloquenthas-manybelongs-to

Update many multiple data with tables hasmany and belongsTo?


sorry for my english

I want two tables

Invoices

  • id
  • user_id
  • name
  • created_at
  • update_at

Invoicesitems

  • id
  • invoice_id
  • title
  • createad_at
  • update_at

Models

class Invoices extends eloquent{
   public function invoicesitems(){
       return $this->hasMany('Invoicesitem');
   }
}

class Invoicesitems extends eloquent{
   public function invoices(){
       return $this->belongsTo('Invoice');
   }
}

Now, for update the items of my invoices? Example my invoices have 5 item, i need update to 10 items

first delete all items of my invoices and insert new ???

$invoices = Invoices::findOrFail($id);
$dataupdate = array(
  'user_id' => Input::get('user'),
  'name' => Input::get('name'),
);
$invoices->fill($dataupdate);
$invoices->save();

//Ok update invoices, now how to update items? Thanks you.


Solution

  • If your business logic allows - you can just replace the invoice items.

    $invoice = Invoices::findOrFail($id);
    $dataupdate = array(
        'user_id' => Input::get('user'),
        'name' => Input::get('name'),
     );
     $invoice->update($dataupdate);
    
     // replace invoice items
     $invoice->invoicesitems()->delete();
     $invoice->invoicesitems()->create($invoiceItems);
    

    Note! This is quite straight solution. You can improve by using insert() method instead of create() for batch insert.