简体   繁体   English

CakePHP保存模型和关联的模型

[英]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 我在数据库中添加了一个名为addresses的表,其中的字段user_idusers.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 : 我尝试将保存功能从save更改为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. CakePHP保存需要更多的工作来跨关系保存。 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';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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