OctoberCMS - 插入时更新相关表中的字段 [英] OctoberCMS - Update a field in a related table when inserting
问题描述
在OctoberCMS中,我有三个表:
学生、课程和订阅(学生 ID、课程 ID、活动)
当学生订阅课程时,它不会被激活,直到管理员激活它.这是合乎逻辑的.但是当管理员从后台打开课程表时,他可以选择学生订阅该课程,然后将他们添加到订阅表中.在这里我想更新字段:自动激活.
我怎么能点那个?
我写了这段代码,但没有用:
In OctoberCMS, I have three tables:
Students, Courses and Subscriptions (studentID, courseID, active)
When student subscribes to a course, it's not activated until the admin activate it. That is logical. But When admin opens a course form from backend, he can select students to subscribe in this course, then they are added to subscriptions table. Here I would like to update the field: active automatically.
How can I dot that?
I wrote this code, but it didn't work:
public function afterSave()
{
foreach($this->students as $student)
{
$student->pivot->is_activated = true;
$student->pivot->save;
}
}
这是@Hardik Satasiya 建议后我的所有代码:
This is all my code after @Hardik Satasiya advice:
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
推荐答案
为此,您需要在 Courses
模型中定义适当的关系
For this you need to define proper relation ship inside the Courses
Model
define Pivot Model
=> Subscriptions
你已经做到了.
define Pivot Model
=> Subscriptions
you already did it.
现在在 Courses
中定义正确的 Relation.型号
Now define proper Relation in Courses
. Model
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();
}
}
这应该有效.如有疑问请评论.
this should work. If any doubts please comment.
这篇关于OctoberCMS - 插入时更新相关表中的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!