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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里