2011-02-16 199 views
1

我有一个用户模型。CakePHP保存模型和关联模型

它含有看起来像这样的形式注册查看:

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) 

这工作。


我添加了一个表,我的数据库与外地user_id称为addresses这是一个外键users.id

我把我的用户模型:

var $hasMany = 'Address'; 

我添加字段,这样到注册表格:

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

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

我试图改变从save保存功能saveAll

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

现在没有得到保存。

我在做什么错?

回答

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让他们成功或失败在一起。如果您不想使用事务,请考虑在请求中途中断时向用户显示的内容。还要考虑数据库将保留在什么状态,以及如何恢复。

+0

这工作,但回避了一个问题:如果在保存用户成功,但保存地址/ profile文件失败 - 怎么办?将他们带回表单将尝试再次创建新用户。 –

+0

如果发生这种情况,@John,我会将它们重定向到一个屏幕,以编辑他们刚刚创建的用户,并将错误显示为一条flash消息。或者,您可以使用一个事务,以便两个插入成功或失败在一起:http://book.cakephp.org/view/1633/Transactions –

+0

感谢您的信息! –

1

您可能还需要把这个地址模型:

var $belongsTo = 'User';