0

在 OctoberCMS 中,我有三个表:
学生、课程和订阅(学生 ID、课程 ID、活动)
当学生订阅课程时,直到管理员激活它才会激活。这是合乎逻辑的。但是当管理员从后端打开一个课程表时,他可以选择学生订阅这个课程,然后他们被添加到订阅表中。在这里我想更新字段:自动激活。
我怎么能点那个?
我写了这段代码,但它没有用:

    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

4

1 回答 1

2

为此,您需要在Courses模型中定义适当的关系

定义Pivot Model=>Subscriptions你已经做到了。

现在在 中定义适当的关系Courses。模型

public $belongsToMany = [
    ....
    'students_pivot_model' => [
        'HardikSatasiya\Plugin\Models\Students', // replace model
        'table' => 'yournamespace_course_student', // replace tb name
        'pivot' => ['is_activated'],
        'timestamps' => true, // if you added times-stamp support
        'pivotModel' => 'HardikSatasiya\Plugin\Models\Subscriptions',
    ],
    ....
];

现在is_activated手动设置

public function afterSave()
{
    foreach($this->students_pivot_model as $pivot_model)
    {
        $pivot_model->pivot->is_activated = true;
        // no validations
        $pivot_model->pivot->forceSave(); 
    }
}

这应该有效。如有任何疑问,请发表评论。

于 2018-05-10T17:27:04.313 回答