我已经成功地能够保存用户和配置文件模型中的数据,问题是在配置文件表中只有id和user_id正在插入,配置文件中的剩余字段,例如,电子邮件,城市是空的。请帮助我对此进行分类,请查找以下代码:
型号:
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'
)
);
....请帮帮忙。
提前感谢!
发布于 2012-03-03 11:54:23
更新您的表单:
<?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)) {很明显,有请求数据,否则您不会通过用户保存。
发布于 2013-09-10 23:07:12
正如Chuck Burgess所说的那样更新表单,另外您还可以这样做:
if ($this->User->saveAll($this->request->data)) {而不是:
if ($this->User->save($this->request->data)) {因此,您不需要在以后保存配置文件。
https://stackoverflow.com/questions/9538551
复制相似问题