hasMany relationship to model and continue use chain methods

Posted 1 year ago by zhezhebie

hey , friends ,when I use laravel5.5 ,I come accross a problem , I have a level ,and there are many lessons belongs to the level ,when I soft delete the level ,I want to change all the lessons which belongs to this level to soft delete status too ,and in production enviroment ,Course->Level->Unit->Lesson ,when I change the parent level ,I want to change all tree child at the same time , could you give me a hand ?

    public function incrementOrDecrementLevelNum($course_level_id, $type = 1)
    {
        $level = CourseLevel::find($course_level_id);
        if ($level) {
            $course = $level->courses;
            $units = $level->courseUnits;
            $lessons = $level->courseLessons;
        } else {
            return false;
        }
        if ($type == 1) {
            $course->increment('level_num');
        } elseif ($type == -1) {
            $course->decrement('level_num');
            $unit_num = $units->count();
            $lesson_num = $lessons->count();
            $course->decrement('unit_num', $unit_num)->decrement('lesson_num', $lesson_num);
            # I want to use model's method ,but laravel tell me this is a collection ,don't have update method .
            $level->update(['status' => 4]);
            $units->update(['status' => 4]);
            $lessons->update(['status' => 4]);
        }
        return true;
    }

relation CourseLevel;

 public function courses()
    {
        return $this->belongsTo('App\Models\Course', 'course_id', 'id');
    }

    /**
     * belongs to many for customer
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     *
     */
    public function courseUnits()
    {
        return $this->hasMany('App\Models\CourseUnit', 'course_level_id', 'id');
    }

    /**
     * belongs to many for customer
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     *
     */
    public function courseLessons()
    {
        return $this->hasMany('App\Models\CourseLesson', 'course_level_id', 'id');
    }

Please sign in or create an account to participate in this conversation.