简体   繁体   中英

Saving HABTM data while also creating new record in related table with CakePHP

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?

您可能希望使用Profile调用saveAll,而不是Hobby。

$this->Profile->saveAll($this->request->data)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM