【发布时间】:2017-08-27 13:38:46
【问题描述】:
在本书的这个例子中:
https://book.cakephp.org/3.0/en/orm/associations.html#using-the-through-option
class StudentsTable extends Table
{
public function initialize(array $config)
{
$this->belongsToMany('Courses', [
'through' => 'CoursesMemberships',
]);
}
}
class CoursesTable extends Table
{
public function initialize(array $config)
{
$this->belongsToMany('Students', [
'through' => 'CoursesMemberships',
]);
}
}
class CoursesMembershipsTable extends Table
{
public function initialize(array $config)
{
$this->belongsTo('Students');
$this->belongsTo('Courses');
}
}
我想输入与课程#8 对应的grade,同时添加一个新的student。我遵循这两个例子:
https://book.cakephp.org/3.0/en/orm/saving-data.html#saving-belongstomany-associations
和
https://book.cakephp.org/3.0/en/views/helpers/form.html#associated-form-inputs
并修改StudentsController.php中的add方法
public function add()
{
$student = $this->Students->newEntity();
if ($this->request->is('post')) {
$student = $this->Students->patchEntity($user, $this->request->getData(), [
'associated' => [
'Courses']]);
if ($this->Students->save($student,['associated' => ['Courses._joinData']])) {
$this->Flash->success(__('The student has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The student could not be saved. Please, try again.'));
}
$courses = $this->Students->Courses->find('list', ['limit' => 200]);
$this->set(compact('student', 'courses'));
$this->set('_serialize', ['student']);
}
和Students/add.ctp 拥有
echo $this->Form->control('courses._ids', ['options' => $courses]);
echo $this->Form->control('courses.5._joinData.grade');
当我在视图中选择课程#8 并输入相应的成绩时,我在CoursesMemberships 表中看不到它。它自己添加记录,但grade 不存在。
【问题讨论】:
标签: php mysql cakephp-3.0 jointable