php - CakePHP 保存模型和关联模型

标签 php mysql cakephp cakephp-1.3 cakephp-model

我有一个用户模型。

它有一个注册 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_idusers.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/

相关文章:

带有 Laravel 的 Php-phantomjs(文件不存在或不可执行 : bin/phantomjs)

php - 从 2 个表中选择所有行,其中 field =?

php - 如何修复CENTOS 7.6上的 ‘No Space Left on Device’错误

javascript - CakePHP 在元素中使用 JsHelper

php - Laravel 内页未加载 -- htaccess 问题

php - 使用 real_escape_string 时用户访问被拒绝

php - MySQL自连接获取有序父子记录

php - 警告 : mysql_select_db(): Access denied for user

java - 将随机整数从java插入到mysql作为唯一ID

php - 锂和验证复杂形式的输入 - 如何?