CakePHP保存模型和相关模型

时间:2011-02-16 21:08:20

标签: php mysql cakephp cakephp-1.3 cakephp-appmodel

我有一个用户模型。

它有一个包含如下形式的注册表视图:

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_id字段是users.id的外键

我输入了我的用户模型:

var $hasMany = 'Address';

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

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

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

我尝试将保存功能从save更改为saveAll

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

现在没有任何东西得救。

我做错了什么?

2 个答案:

答案 0 :(得分:4)

CakePHP保存需要更多的工作来保存跨关系。这是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);
        }
    }
}
?>

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

答案 1 :(得分:1)

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

var $belongsTo = 'User';

相关问题