3

I'm building a site that works as a social network.

I have a profiles table and a Profile model.

Profile HABTM Interests

Profile HABTM Hobbies etc...

There are a couple of pre-defined records in the hobbies and interests tables, which users can choose from to display on their profile. But they also have the option to add their own hobbies and interests if theirs isn't pre-defined.

A problem arises when the user chooses to add a hobby or interest which doesn't exist yet. Saving the pre-defined records to the join table is not a problem. But I can't seem to create new entries in the interests and hobbies tables during the same save call.

Below is a snippet of the data array I've tried to save (I've also tried other combinations, but this one seems the most logical):

array(
    'Interests' => array(
        'Interests' => array(
            (int) 0 => '1',
            (int) 1 => '2',
            (int) 2 => '5'
        ),
        'name' => 'Internet' //this is the user-created entry
    ),
    'Hobbies' => array(
        'Hobbies' => array(
            (int) 0 => '1',
            (int) 1 => '2',
            (int) 2 => '5',
            (int) 3 => '7',
            (int) 4 => '8'
        ),
        'name' => 'Reading' //this is also a user-created entry
    )
)

The save function: $this->Profile->saveAll($this->request->data, array('deep' => true))

The problem is that the new entries (in this case "Reading" and "Internet") are being ignored during the save. There is no error and everything else is being saved just fine.

If I call $this->Profile->Hobby->saveAll($this->request->data) then it does work, but only for the Hobby model. The new interest is ignored of course, because the save call doesn't go through its model.

Is the data array not formatted correctly, or is this just not possible to achieve in one save call?

Botch
  • 419
  • 5
  • 19
  • did you try saveAssociated ? – Ayo Akinyemi Oct 01 '13 at 15:10
  • 1
    Saving HABTM data in CakePHP can be painful : http://patisserie.keensoftware.com/en/pages/how-to-save-habtm-data-in-cakephp – Chris Oct 02 '13 at 12:09
  • Yeah, I ended up using that method. A point to note: it doesn't play well with the Form Helper, because it assumes a different array structure. – Botch Oct 07 '13 at 12:26

1 Answers1

0

You might want to call saveAll using Profile, not Hobby. 

$this->Profile->saveAll($this->request->data)
Arno Chauveau
  • 990
  • 9
  • 14
Guillermo Mansilla
  • 3,779
  • 2
  • 29
  • 34