1

假设我有 3 张桌子property_details, property_feature_details, property_feature_relations.

PropertyDetail 模型与 PropertyFeatureRelation 具有 hasMany 关系。

当时保存我的数据数组如下所示:

$this->data = array('PropertyDetail' => array('name'=>'xyz'),'PropertyFeatureRelation' => array('0' => array('feature_id'=>1),'1' => array('feature_id'=>5),'2' => array('feature_id'=>0),'3' => array('feature_id'=>0)));

这些 feature_ids 值来自复选框。那些已检查它们包含 ids 值,未检查的值为 0。但在子表中保存所有数据为零和非零。

实际上我想保存那些只被选中的复选框值。请不要提供任何手动控制器逻辑。帮我。

4

1 回答 1

0

我正在用我的例子来解释你,这个例子有问题、答案和调查

您可以使用多个复选框语法,如下所示:

                                             $answers=array();
                                    $tmp_ans=$question['Answer'];
                                    for($j=0;$j < count($tmp_ans);$j++)
                                    $answers[$tmp_ans[$j]['id']]=$tmp_ans[$j]['answer'];            
                                    echo '<li>';
                                        echo $this->Form->input('Answer', array(
                                        'type' => 'select',
                                        'name'=>'Answer['.$question['Question']['id'].']',
                                        'class'=>'test',
                                        'label'=>false,
                                        'multiple' => 'checkbox',
                                        'options' =>$answers ,
                                        ));

                                    echo '</li>';

之后,您将只有那些您检查过的答案,其他人不会出现在帖子数组中,因此要保存数据,您可以使用以下语法

if(!empty($this->data['Answer'])){

                foreach ($this->data['Answer'] as $key=>$val):

                    if(!empty($val)):
                            if(is_array($val)):

                                foreach ($val as $ans):
                                    $post_data['UserAnswer']['id']='';
                                    $post_data['UserAnswer']['survey_id']=$id;
                                    $post_data['UserAnswer']['user_id']=$this->Auth->user('id');
                                    $post_data['UserAnswer']['question_id']=$key;
                                    $post_data['UserAnswer']['answer_id']=$ans;
                                    $this->UserAnswer->save($post_data['UserAnswer']);
                                endforeach;
                            else:
                                    $post_data['UserAnswer']['id']='';
                                    $post_data['UserAnswer']['survey_id']=$id;
                                    $post_data['UserAnswer']['user_id']=$this->Auth->user('id');
                                    $post_data['UserAnswer']['question_id']=$key;
                                    $post_data['UserAnswer']['answer_id']=$val;
                                    $this->UserAnswer->save($post_data['UserAnswer']);

                            endif;

                    endif;
                endforeach;

            }
于 2013-02-26T06:33:05.377 回答