我有一个用户模型。
它有一个注册 View ,包含一个如下所示的表单:
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)
现在什么都不会保存。
我做错了什么?
最佳答案
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让他们一起成功或失败。如果您不想使用事务,请考虑当请求中途失败时向用户显示的内容。还要考虑数据库将处于何种状态,以及如何恢复。
关于php - CakePHP 保存模型和关联模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5022117/