1

我有一个用户模型。

它有一个注册视图,其中包含一个如下所示的表单:

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

当您提交表单时,它会保存如下:

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

这行得通。


我在我的数据库中添加了一个表,该表使用作为外键addresses的字段调用user_idusers.id

我放入了我的用户模型:

var $hasMany = 'Address';

我将这样的字段添加到注册表单:

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

我希望这会在地址表中创建一个新条目并将其与新用户相关联。它不会,它会创建一个新用户,但不会在地址表中放置任何内容。

我尝试将保存功能从更改savesaveAll

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

现在什么都没有得救。

我究竟做错了什么?

4

2 回答 2

4

CakePHP 保存需要更多的工作才能跨关系保存。这是文档中的一个示例

<?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);
        }
    }
}
?>

当您进行多个数据库更改时,您应该考虑使用事务来使它们一起成功或失败。如果您不想使用事务,请考虑在请求中途失败时向用户显示的内容。还要考虑数据库将处于什么状态,以及如何恢复。

于 2011-02-16T21:13:12.270 回答
1

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

var $belongsTo = 'User';

于 2011-02-16T21:40:30.220 回答