Bal*_*mbi 5 php mysql orm associations cakephp-3.0
我有两张桌子.我的主要表是学生.我的次要表是考试.我正在尝试使用hasMany和belongsToMany Association 保存这两个表.但它仅在学生表中保存数据,而不是在考试中保存.任何人都可以帮我解决这个问题.
学生型号:
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']);
}
}
Run Code Online (Sandbox Code Playgroud)
考试模型:
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']);
}
}
Run Code Online (Sandbox Code Playgroud)
我的school.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();
Run Code Online (Sandbox Code Playgroud)
在我的控制器中:
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.'));
}
}
}
Run Code Online (Sandbox Code Playgroud)
您需要确保您能够安排考试。设置accessibleFields以允许您修补关联数据
$student = $this->Students->patchEntity(
$student, $this->request->data, [
'associated' => ['Exams'],
'accessibleFields' => ['exams' => true]
]
);
Run Code Online (Sandbox Code Playgroud)
您还可以使用实体中的 $_accessible 属性来执行此操作。
| 归档时间: |
|
| 查看次数: |
703 次 |
| 最近记录: |