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?

Answers


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

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

Need Your Help

Validate an XmlDocument using an XSD String in C#?

c# xml validation xsd xmldocument

I have an XmlDocument in C# that I need to validate against an Xml Schema. I've seen a lot of articles on how to do this using XmlDocument.Schemas.Add(namspace, xsdfilename), however my XSD is not ...

RSpec TextMate Bundle

ruby rspec textmate textmatebundles

So I updated to the latest RSpec TextMate Bundle and I'm no longer able to run spec test with "Command R".

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.