2012-09-26 92 views
1

我有两个模型,关系为Advisor belongsTo RoomRoom hasMany AdvisorAdvisor在数据库(Advisor.room_id)中有一个指向特定房间的外键约束。此值的默认值为NULL值(表示没有房间的顾问)。无法在CakePHP中使用复选框保存所有数据

假设我有一个Advisor,room_id设置为n。我现在想从Advisor取消分配的nth室 - 使用选择字段,我可以重置room_idNULL,具有以下request->data结构:

[Room] => Array 
    (
     [name] => TestRoom2 
     [type] => single suite 
     [id] => 4 
    ) 

[Advisor] => Array 
    (
     [0] => Array 
      (
       [id] => 14 
       [room_id] => 
       [name] => foo 
      ) 
    ) 

然而,当我试图通过复选框的使用要做到这一点与生成的$this->request->data相同,MySQL拒绝更新NULL的值。

另外,在第二种情况下,似乎在request->data中明确更改room_id的值不起作用。但是,如果我将Advisor.0.name更改为hax(通过直接修改request->dataname字段确实保存。

我保存通过调用$this->Room->saveAll($request->data, array('deep' => true)) - 无论是在选择字段和复选框的情况下。

我通过多次调用Form帮手产生一系列的复选框的:

$count = 0; 
// $key is the Advisor id, and $attributes is an array of the form 
//  array('name' => (string), 'disabled' => (bool)) 
foreach($options['advisorList'] as $key => $attributes) { 
    $form[] = $this->Form->hidden(sprintf('Advisor.%s.id', $count), array('value' => $key)); 
    $form[] = $this->Form->input(sprintf('Advisor.%s.room_id', $count), array(
     'type' => 'checkbox', 
     'label' => $attributes['name'], 
     'disabled' => $attributes['disabled'])); 
    $count++; 
} 

此外,如果room_id已经被设置为NULL,是没有问题的设置room_id - 除了,room_id会不管复选框是否被选中。

任何帮助将不胜感激 - 谢谢!

回答

0

解决!这与CakePHP $ model-> saveAll()具有许多关系有关。

为了正确地更新这种形式,所有的参赛者是可以在白水(改变)必须撤消他们的关系到各自的房间,并保存在数据库中

foreach($copyOfData['Advisor'] as $advisor) { 
    $advisor['room_id'] = null; 
    $this->Advisor->save(array('Advisor' => $advisor)); 
} 

只有在这项工作已经完成,我们可以拨打$this->Advisor->saveAll($this->request->data, array('deep' => true))并且saveAll()的行为如预期。

相关问题