简体   繁体   中英

Relation Limit [ octobercms ]

I have a model called Lessons and it has a belongsToMany relationship called students with a table called students_for_lesson . Lesson model has fields called number_of_students and number_of_enrollments for each lesson.

what I want is to give a message stopping Add students for the lesson when number_of_enrollments value reaches number_of_students value.

One way is to listen to the Model relation events ( BelongsToMany ) : beforeAttach , afterAttach , beforeDetach , afterDetach

In this case if you need to run some validations before creating the relationship then use the beforeAttach event:

LessonModel::extend(function ($model) {

    /** Before Attach */
    $model->bindEvent('model.relation.beforeAttach', function ($relationName, $attachedIdList, $insertData) use ($model) {

        // Student => Lesson Relation
        if ($relationName === 'your-lesson-student-relation-name') {

            // Check Number of enrollments & other stuff ...

            // throw new \ApplicationException('Cannot add student. Maximum number of enrollments reached.');
        }

    });

});

See this SO post & here about extending models

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM