views:

3634

answers:

2

Heyall,

I am using a very intrinsic database with a CakePHP application and so far my multi-models views and controllers are working fine. I have a singular table (Entity) that have it's id on several other tables as the Foreign Key entity_id

Some tables are one to one relations (Like a Company is one Entity) and some are one to many (Entity can have several Addresses) and so on.

I won't/can't change the database model, so this is the structure.

I have been using saveAll() to save data on those tables with input names like:

Entity.type='x' (hidden inside the view)
Company.name
Address.0.street
Address.0.city
Address.1.street
Address.1.city

... and so on ...

and my save all is doing all the hard job, BEGIN TRANSACTION, all INSERTs and a final COMMIT ...

But now I've created a EntityCategory that is a n to n relation and created the full HABTM relation inside the model.

It works when I save() it but just the HABTM relation, and it saves everthing when I use saveAll() (just as before) except for the HABTM relation.

Am I missing something ? How I make this work correctly ? I am using the following code today:

if (!empty($this->data)) {
  $this->Entity->saveAll($this->data);
  $this->Entity->save($this->data);
}

The saveAll() saves all data in several tables, saves the id in Entity->id and the save() saves the HABTM relations, but I am not sure if it is correct or if it can bring me problems if I change some structure/model.

Is this the best way to use it? Is there a correct way to save that relations inside CakePHP ? What your experience/knowledge can tell me ?

A: 

The problem with saveAll() and HABTM associations is a known CakePHP issue, and has not been resolved as of 1.2 RC2.

As fas as best pratices for saving related model data goes, according to the CakePHP cookbook:

"When working with associated models, it is important to realize that saving model data should always be done by the corresponding CakePHP model. If you are saving a new Post and its associated Comments, then you would use both Post and Comment models during the save operation."

However, using saveAll() and save() should work, and IMHO is a more flexible/generic solution.

Jacob
+1  A: 

This is fixed if you download the nightly.

Be careful though, something else might break.

Chris Hawes