我有两张表。我的主要表格是学生。我的第二张表是考试。我正在尝试使用hasMany和belongsToMany联来保存这两个表。但它只将数据保存在学生表中,而不是考试中。有谁能帮我解决这个问题吗。
学生模型:
class StudentsTable extends Table {
public function initialize(array $config) {
$this->addBehavior('Timestamp');
parent::initialize($config);
$this->table('students');
$this->primaryKey(['id']);
$this->hasMany('Exams', [
'className' => 'Exams',
'foreignKey' => 'student_id',
'dependent'=>'true',
'cascadeCallbacks'=>'true']);
}
}
考试模式:
class ExamsTable extends Table {
public function initialize(array $config) {
parent::initialize($config);
$this->table('exams');
$this->primaryKey(['id']);
$this->belongsToMany('Students',[
'className'=>'Students',
'foreignKey' => 'subject_id',
'dependent'=>'true',
'cascadeCallbacks'=>'true']);
}
}
我的学校.ctp:
echo $this->Form->create();
echo $this->Form->input('name');
echo $this->Form->input('exams.subject', array(
'required'=>false,
'multiple' => 'checkbox',
'options' => array(
0 => 'Tamil',
1 => 'English',
2 => 'Maths')));
echo $this->Form->button(__('Save'));
echo $this->Form->end();
在我的控制器中:
public function school() {
$this->loadModel('Students');
$this->loadModel('Exams');
$student = $this->Students->newEntity();
if ($this->request->is('post')) {
$this->request->data['exams']['subject'] =
implode(',',$this->request->data['exams']['subject']);
$student = $this->Students->patchEntity(
$student, $this->request->data, ['associated' => ['Exams']]
);
if ($this->Students->save($student)) {
$this->Flash->success(__('The user has been saved.'));
} else {
$this->Flash->error(__('Unable to add the user.'));
}
}
}
修补归属到多个关联
你需要确保你能够设置考试。设置accessibleFields以允许您修补关联的数据
$student = $this->Students->patchEntity(
$student, $this->request->data, [
'associated' => ['Exams'],
'accessibleFields' => ['exams' => true]
]
);
您也可以使用实体中的$_accessible属性来执行此操作。
我从来没有做过hasMany to belongsToMany,因为我不认为它是那样工作的(我的意思是无害的。)但我会尽力解释。你们的关系应该都属于ToMany,因为考试会有很多学生,学生也会有很多考试。所以基本上,无论哪种方式,它们都是一样的。你需要的是另一个表来连接它们,它将被称为students_exams
或exams_students
(我认为它是exams_students,因为E在S之前),因为在蛋糕中,如果你正确地命名所有东西,大部分都会自动发生。
假设您知道patchEntity
的工作原理,正确创建$this->request->data
将自动对其进行修补,并在保存时将其保存在正确的表中。如果您还有任何问题,请随时询问。:)