rookian
rookian

Reputation: 1064

Saving multiple hasMany through at once

I have a many-to-many relation between 2 models Invoiceand Position defined with the hasMany through method like described in the Cookbook.

Now when i create a Invoice, i want to save multiple Positions to that Invoice in one save()-operation. Something like this:

$data = array(
  'Invoice' => array(
    // invoice stuff 
  ),
  'InvoicesPosition' => array(
    [0] => array(
      // additional meta information
      'Position' => array(
        // position stuff
        // ...
      ),
    ),
    [1] => array(
      // ...
      'Position' => array(
        // position stuff
        // ...
      ),
    ),
    // and so on
  ),
);  

$this->Invoice->saveAll($data, array('deep' => true));

The result should be one new Invoice, with 2 Positions linked to it (That means 1 new record in the invoices table, 2 new records in the positions table and 2 new records in the join table).

Is it possible with Cake's built-in methods? Or do i have to overwrite the saveAll()-method for that model?

Upvotes: 1

Views: 1177

Answers (1)

Arun Jain
Arun Jain

Reputation: 5464

Use 'deep' => true option in saveAll() method.

$this->Invoice->saveAll($data, array('deep' => true));

Upvotes: 1

Related Questions