在这本书的例子中:

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');
    }
}


我想在添加新的grade的同时输入与课程#8相对应的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

并修改add中的StudentsController.php方法

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不存在。

最佳答案

您不能混合使用特殊的_ids语法和传统的语法来表示嵌套的数据结构,即property.index.field...(文档中有关该行为的注释可能不会受到伤害)。

另外,在索引5处添加数据似乎非常随意,您要添加新的链接/记录,因此通常从0开始。

放弃_ids语法,并通过显式定义其主键来构建适当的课程数据集,例如:

echo $this->Form->control('courses.0.id', ['type' => 'select', 'options' => $courses]);
echo $this->Form->control('courses.0._joinData.grade');


也可以看看


Cookbook > Database Access & ORM > Saving Data > Saving Additional Data to the Join Table
Cookbook > Views > Helpers > Form > Creating Inputs for Associated Data

关于php - 在CakePHP 3.0的add方法中将其他数据保存到联接表中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45905543/

10-16 06:48