【问题标题】:Saving Additional Data to the Join Table in the add method in CakePHP 3.0在 CakePHP 3.0 的 add 方法中将附加数据保存到连接表
【发布时间】: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


    【解决方案1】:

    您不能混合使用特殊的 _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');
    

    另见

    【讨论】:

    • 非常感谢!正是缺少的东西。现在一切顺利。
    【解决方案2】:

    起初我在你的 add 函数中没有看到 $course...

    如果你将站点更改为 $courses

    $items = $this->学生->课程->find('list', ['limit' => 200]);

    或者在你看来:

    echo $this->Form->control('courses._ids', ['options' => $items]);
    

    【讨论】:

    • 不,那是印刷错误,我编辑了问题。这里没有项目,只有课程。
    猜你喜欢
    • 2015-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多