简体   繁体   中英

CakePHP save model and associated model

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?

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.

您可能还需要将其放入“地址”模型中:

var $belongsTo = 'User';

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