OctoberCMS - 插入时更新相关表中的字段

时间:2018-05-08 20:19:58

标签: octobercms octobercms-backend october-form-controller

在OctoberCMS,我有三张桌子:
学生,课程和订阅(studentID,courseID,活跃)
当学生订阅课程时,在管理员激活课程之前,它不会被激活。这是合乎逻辑的。但是当管理员从后端打开课程表单时,他可以选择学生在本课程中订阅,然后将它们添加到订阅表中。在这里,我想更新字段:自动激活。
我怎么能点到那个?
我写了这段代码,但它没有工作:

    public function afterSave()
    {
        foreach($this->students as $student)
        {
            $student->pivot->is_activated = true;
            $student->pivot->save;
        }
    }

编辑:

在@Hardik Satasiya的建议之后,这是我的所有代码:

    class Course extends Model
    {
      public $belongsToMany = [
        'students'=>[
                'Sunsoft\Courses\Models\Student', 
                'table'=>'sunsoft_courses_student_course', 
                'order'=>'users.name', 
                'scope'=>'students',
                'timestamps' => true,
                'pivot'=>['id', 'is_activated'],
                'pivotModel'=>'Sunsoft\Courses\Models\StudentCourse',
        ],
      ];

      public function afterSave()
      {
        foreach($this->students as $student)
        {
            $student->pivot->is_activated = true;
            $student->pivot->save;
            $student->save;
        }
      }
    }

    class Student extends User
    {
      public $belongsToMany = [
        'courses'=>[
            'sunsoft\courses\models\Course', 
            'table'=>'sunsoft_courses_student_course', 
            'order'=>'sunsoft_courses_courses.name',
            'pivot'=>['id', 'is_activated'],
            'timestamps' => true,
            'pivotModel'=>'Sunsoft\Courses\Models\StudentCourse',
        ],
      ];
     }

     class StudentCourse extends Model
     {
        public $belongsTo= [
          'course'=>['sunsoft\courses\models\Course'],
          'student'=>['sunsoft\courses\models\Student', 'scope'=>'students', 'order'=>'users.name'],
        ];      
    }

这是我得到的错误:
http://prntscr.com/jhrfzu

0 个答案:

没有答案