CakePHP-保存关联的模型数据
我有两个模型。。一个叫做CakePHP-保存关联的模型数据,php,cakephp,Php,Cakephp,我有两个模型。。一个叫做Schedule,另一个叫做ScheduleContact SchedulebelongsToSchedule联系人 从属于scheduleController的一个操作中,我希望为主模型以及关联模型保存来自序列化表单的值 在我看来,我有以下几点 <?php echo $this->Form->input('Schedule.start_at', array('id' => 'start_at', 'type' => 'hidden'));
Schedule
,另一个叫做ScheduleContact
Schedule
belongsToSchedule联系人
从属于scheduleController的一个操作中,我希望为主模型以及关联模型保存来自序列化表单的值
在我看来,我有以下几点
<?php echo $this->Form->input('Schedule.start_at', array('id' => 'start_at', 'type' => 'hidden')); ?>
<?php echo $this->Form->input('Schedule.finish_at', array('id' => 'finish_at', 'type' => 'hidden')); ?>
<?php echo $this->Form->input('ScheduleContact.0.name', array('id' => 'name','div' => 'inline-input')); ?>
<?php echo $this->Form->input('ScheduleContact.0.surname', array('id' => 'surname','div' => 'inline-input compact')); ?>
最后,我尝试这样保存数据:
if($this->Schedule->saveAssociated($this->request->data)){
它不会将任何内容保存到数据库中,因此从未满足此if条件
有什么问题吗?感谢基本上,问题是saveAssociated需要在主模型中应用。考虑到这一点,如上所述,主模型有一个bolongsTo关系,这意味着当前模型包含外键。,这也是正确的。那么问题出在哪里呢不问 问题是saveAsocciated相当于
$user = $this->User->save($this->request->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->request->data['Profile']['user_id'] = $this->User->id;
}
这意味着它首先尝试保存主模型。因此,我的设置不正确,因为主模型需要是ScheduleContact
,因为在ScheduleContact
id中成功插入数据后,外键将保存在ScheduleContact
模型中
好了……一旦你通过了学习曲线,CakePHP就很棒了。你的模型名打破了Cake的命名惯例。它应该是: 预定联系人 以下几个问题可以为您提供更好的答案:
- 能否添加模型关联变量($belongsTo等)
- 您是否使用可控制行为
$user = $this->User->save($this->request->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->request->data['Profile']['user_id'] = $this->User->id;
}