Laravel模型事件观察者

时间:2018-11-29 13:40:08

标签: laravel events model observers

我有3张桌子: 成员(ID,名字) lesson_member(id,member_id,lesson_id,注释) 课程(id,date_time,完整) 当我在数据透视表(lesson_member)中插入/删除或更新记录时,我想检查该课程是否具有最多的成员。如果是,则字段满必须为true,否则为false。 我认为最好的方法是使用观察员。 这是我的观察者:

updateFullLesson($ lessonLicenseMember);         }

    public function deleting(LessonLicenseMember $lessonLicenseMember)
    {
        $this->updateFullLesson($lessonLicenseMember);
    }

    public function updateFullLesson(LessonMember $lessonMember): void
    {
        $maxMembers = $lessonMember->lesson->course->type->max_members;
        $countActualMembers = LessonMember::where('lesson_id', $lessonMember->lesson->id)->count();
        $lesson=Lesson::find($lessonMember->lesson->id);
        if ($countActualMembers + 1 >= $maxMembers) {
            $lesson->full = true;
        } else {
            $lesson->full = false;
        }
        $lesson->save();
    }
}

这是控制器中的3个功能:

 <?php
 public function removeMember($lessonMemberId)
    {
        $lessonMember=LessonMember::findOrFail($lessonMemberId);
        $lesson=$lessonMember->lesson;
        $lessonMember->delete();
        return redirect()->route('lessons.edit',['lesson'=>$lesson->id])->with('id',trans('lesson.member_removed'))->withInput(['tab'=>'tab2']);
    }


     public function editLessonLicenseMember($lessonLicenseMemberId,Request $request)
    {

        $lessonMember=LessonMember::findOrFail($lessonLicenseMemberId);
        $lessonMember->notes=$request->notes;
        $lessonMember->save();

        //return redirect()->route('lessons.edit',['lesson'=>$lesson->id])->with('id',trans('lesson.member_removed'))->withInput(['tab'=>'tab2']);
    }

    public function addMember(Request $request)
    {
        $lessonMember=new LessonMember();

        $lessonId = $request->session()->get('lessonId',1);

        if((!($lessonMember::where('lesson_id','=',$lessonId)
            ->where('license_member_id','=',$request->licenseMemberId)
            ->exists()))) {

            $lessonMember->lesson_id = $lessonId;
            $lessonMember->license_member_id = $request->licenseMemberId;
            $lessonMember->save();

    }

当我尝试该程序时,它没有给我任何错误,但是数据库中的字段从未更改。

0 个答案:

没有答案