CakePHP save model and associated model

4.7k Views Asked by At

I have a User model.

It has register view containing a form that looks like this:

echo $this->Form->create('User',array(NULL,NULL,'class' => 'signinform'));
echo $this->Form->input('first_name');
...
echo $this->Form->end('Create Account');

When you submit the form, it saves like this:

$this->User->save($this->data)

This works.


I added a table to my database called addresses with the field user_id that is a foreign key to users.id

I put in my Users model:

var $hasMany = 'Address';

I add fields like this to the register form:

echo $this->Form->input('Address.city');

I expected this to create a new entry into the addresses table and associate it with the new user. It does not, It creates a new user, but puts nothing in the addresses table.

I tried changing the save function from save to saveAll:

$this->User->saveAll($this->data)

Now nothing gets saved.

What am I doing wrong?

2

There are 2 best solutions below

2
On BEST ANSWER

CakePHP saving needs a bit more work to save like that across relationships. Here's an example from the documentation.

<?php
function add() {
    if (!empty($this->data)) {
        // We can save the User data:
        // it should be in $this->data['User']

        $user = $this->User->save($this->data);

        // If the user was saved, Now we add this information to the data
        // and save the Profile.

        if (!empty($user)) {
            // The ID of the newly created user has been set
            // as $this->User->id.
            $this->data['Profile']['user_id'] = $this->User->id;

            // Because our User hasOne Profile, we can access
            // the Profile model through the User model:
            $this->User->Profile->save($this->data);
        }
    }
}
?>

When you make more than one database change, you should consider using transactions to make them succeed or fail together. If you don't want to use transactions, consider what you will display to the user when the request fails part way through. Also consider what state the database will be left in, and how you can recover.

0
On

You might also need to put this in the Address model:

var $belongsTo = 'User';