[英]CakePHP save model and associated model
我有一个用户模型。
它具有包含如下形式的注册视图:
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保存需要更多的工作来跨关系保存。 这是文档中的示例 。
<?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);
}
}
}
?>
当您进行多个数据库更改时,应该考虑使用事务来使它们一起成功或失败。 如果您不想使用事务,请考虑当请求部分失败时将显示给用户的内容。 还请考虑将数据库保留在什么状态,以及如何恢复。
您可能还需要将其放入“地址”模型中:
var $belongsTo = 'User';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.