doubiao7410 2019-06-26 13:45
浏览 36
已采纳

与Eloquent / Laravel的复杂关系

Same story as many other questions on this site: I've banged my head into the wall for hours on end trying to figure out these relationships.

I have 3 models where the relationship should work like this:

Model: User
User can belong to many schools.
User belongs to one “Role” separately on each school.
User can be activated/deactivated separately on each school.

Model: School.
School can belong to many users

Model: Role.
Roles would be “Standard” or “Administrator”.

I have a pivot table that connects users and schools. On the pivot table, I've also experimented with adding 'role_id' and 'is_activated' columns - which I doubt is the correct way about doing this?


I want to access data like this:

User
Get schools belonging to the user.
Get role for current school.
Get activated/deactivated status for current school.

School
Get all users belonging to the school.
Get role for each user.
Get activated/deactived status for each user.


I would've solved this if users could only belong to one school each, but since the same user can belong to several schools it got too complicated for me.

What kind of relationships should I apply on each model?

I would very much appreciate if anyone can point me in the right direction here. Thanks!

  • 写回答

1条回答 默认 最新

  • doulu3865 2019-06-26 13:51
    关注

    You can have a many-to-many relationship between user and school. This would require a pivot table between them to store the ids of the two models. At the end your relationship from a user point of view will end up being:

    public function schools() {
      return $this->belongsToMany('App\Models\School', 'pivot_table', 'user_id', 'school_id');
    }
    

    You can have a look at laravel docs on Many-to-Many

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)