这个问题可能重复。但我对一些问题和教程感到困惑。
我尝试使用以下代码保存数组。
$data = array(
'name' => 'ques 1',
'description' => 'lskjdf sldkfj sdlfkjsd flskdjf sldkfjsd',
'objective' => 'jd ldkjf sldkf sldfj sdlfjdlsfsjfl ds',
'Question' => array(
'type' => 'BOOLEAN',
'body' => 'slkdjfs dflskdf slkfjsiuwsdjkf sd',
'Answer' => array(
'body' => 'sd fsldkjfs dddd ddd ddd'
),
),
);
$this->Questionnaire->create();
$this->Questionnaire->saveAll($data);
运行后,此代码问卷已保存3个问题,但没有任何答案。只有一个问题具有身体价值。
这是我的模特课。
Questionnaire.php
<?php
App::uses('AppModel', 'Model');
/**
* Questionnaire Model
*/
class Questionnaire extends AppModel {
/**
* Validation rules
*
* @var array
*/
public $validate = array(
'name' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'Name is required'
)
),
'description' => array(
),
'objective' => array(
),
);
public $hasMany = array(
'Question' => array(
'className' => 'Question',
'foreignKey' => 'questionnairy_id'
),
);
}
Question.php
<?php
App::uses('AppModel', 'Model');
/**
* Question Model
*/
class Question extends AppModel {
/**
* Validation rules
*
* @var array
*/
public $validate = array(
'type' => array(
'valid' => array(
'rule' => array('inList', array(
BOOLEAN_ANSWER,
SINGLE_ANSWER,
MULTIPLE_ANSWER,
)),
'message' => 'Invalide type',
)
),
'body' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'Question is required'
)
),
);
public $belongsTo = array(
'Questionnaire' => array(
'className' => 'Questionnaire',
'foreignKey' => 'questionnaire_id'
),
);
public $hasMany = array(
'Answer' => array(
'className' => 'Answer',
'foreignKey' => 'question_id'
),
);
}
Answer.php
<?php
App::uses('AppModel', 'Model');
/**
* Answer Model
*/
class Answer extends AppModel {
/**
* Validation rules
*
* @var array
*/
public $validate = array(
'body' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'Answer is required'
)
),
);
public $belongsTo = array(
'Question' => array(
'className' => 'Question',
'foreignKey' => 'question_id'
),
);
}
我需要知道保存这个数组的正确方法。请帮我。
答案 0 :(得分:2)
您需要正确格式化阵列。 $data
数组应如下所示:
array(
'Questionnaire' => array(
'name' => 'Questionnaire 1'
),
'Question' => array(
array(
'type' => 'BOOLEAN',
'body' => 'Is Cake sweet?',
'Answer' => array(
array(
'body' => 'Yes.'
)
)
),
array(
'type' => 'BOOLEAN',
'body' => 'Does Cake make things easy and fast?',
'Answer' => array(
array(
'body' => 'Yes.'
)
)
),
)
);
请注意,Question位于索引数组中(与Answer相同)。这是因为他们的关系是hasMany。
表单看起来像这样:
$this->Form->create('Questionnaire');
$this->Form->input('Questionnaire.name');
$this->Form->input('Question.0.type');
$this->Form->input('Question.0.body');
$this->Form->input('Question.0.Answer.0.body');
$this->Form->input('Question.1.type');
$this->Form->input('Question.1.body');
$this->Form->input('Question.1.Answer.0.body');
$this->Form->end();
最后,你需要告诉Cake保存时继续:
$ this-&gt;调查问卷 - &gt; saveAll($ data,array('deep'=&gt; true));
查看书籍以获取更多信息: