【问题标题】:Relation Limit [ octobercms ]关系限制 [ octobercms ]
【发布时间】:2019-08-16 18:16:51
【问题描述】:

我有一个名为Lessons 的模型,它有一个名为studentsbelongsToMany 关系和一个名为students_for_lesson 的表。每个课程的课程模型都有名为 number_of_studentsnumber_of_enrollments 的字段。

我想要的是在number_of_enrollments 值达到number_of_students 值时发出一条消息,停止为课程添加学生。

【问题讨论】:

    标签: octobercms octobercms-plugins october-partial


    【解决方案1】:

    一种方法是监听模型关系事件(BelongsToMany):beforeAttachafterAttachbeforeDetachafterDetach

    在这种情况下,如果您需要在创建关系之前运行一些验证,请使用beforeAttachevent:

    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.');
            }
    
        });
    
    });
    

    看到这个SO post 和这里关于extending models

    【讨论】:

      猜你喜欢
      • 2019-12-05
      • 1970-01-01
      • 1970-01-01
      • 2021-08-25
      • 2020-01-15
      • 2016-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多