CakePHP:无法保存关联的模型数据(HasOne关联)

时间:2012-03-02 18:32:35

标签: cakephp-2.0

我已成功将数据保存在User和Profile模型中,问题是在Profile表中只有id和user_id被插入,配置文件中的剩余字段,例如email,city为NULL。请帮我整理一下,请找到以下代码:

型号:

user.php的:

class User extends AppModel {
public $name = 'User';

var $hasOne = array('Profile' =>
                    array('className'    => 'Profile',
                          'conditions'   => '',
                          'order'        => '',
                          'dependent'    =>  true,
                          'foreignKey'   => 'user_id'
                    )
              );
.....

UsersController.php:

class UsersController extends AppController {
.....
public function add() {
    if ($this->request->is('post')) {
        $this->User->create();
        if ($this->User->save($this->request->data)) {
            if (!empty($this->request->data)) {
                $this->request->data['Profile']['user_id'] = $this->User->id;
                $this->User->Profile->save($this->request->data);
            }
            $this->Session->setFlash(__('The user has been saved'));
            $this->redirect(array('controller' => 'homes','action' => 'index'));
        } else {
            $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
        }
    }
}

查看:add.ctp

            <?php echo $this->Form->create('User' , array('action' => 'add'));?>
            <fieldset>
                <?php
                    echo $this->Form->input('username');
                    echo $this->Form->input('password');
                    echo $this->Form->input('profile.firstname');
                    echo $this->Form->input('profile.lastname');
                    echo $this->Form->input('profile.email');
                ?>
            </fieldset>
            <?php echo $this->Form->end(__('Submit'));?>

型号:Profile.php:

class Profile extends AppModel {
public $name = 'Profile';
var $belongsTo = array('User' =>
                       array('className'  => 'User',
                             'conditions' => '',
                             'order'      => '',
                             'foreignKey' => 'user_id'
                       )
                 );
....

请帮忙。

提前致谢!!!

2 个答案:

答案 0 :(得分:1)

更新您的表单:

           <?php
                echo $this->Form->input('username');
                echo $this->Form->input('password');
                echo $this->Form->input('Profile.firstname');
                echo $this->Form->input('Profile.lastname');
                echo $this->Form->input('Profile.email');
            ?>

此外,以下if语句是过度杀伤:

if (!empty($this->request->data)) {

显然有请求数据,或者你没有超过用户保存。

答案 1 :(得分:0)

按Chuck Burgess的说法更新您的表单,另外您可以这样做:

if ($this->User->saveAll($this->request->data)) {

而不是:

if ($this->User->save($this->request->data)) {

所以你以后不需要保存个人资料。