Laravel:用于多种用户类型,多态关系的表结构 [英] Laravel: Table structure for multiple users types, polymorphic relationships

查看:81
本文介绍了Laravel:用于多种用户类型,多态关系的表结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的网站(使用laravel 5.6和laravel护照的api)中,我有两种类型的用户(教师和学生),将来会有更多类型的用户.教师和学生实体非常不同,这意味着如果我将它们全部放在一个表中,则该表将很长,并且许多字段的值为空.现在,我有一个具有公用字段的Users表,还有另外两个表(Teachers和Students),我已经与user建立了多态关系.我的问题是这是一个好方法,还是还有其他方法可以更优雅地处理此问题?

In my site (api using laravel 5.6 and laravel passport) I have two types of users (Teachers and Students), in the future there will be more. The teacher and student entities are very different, meaning that if I keep them all in one table, the table will be long and many fields will have a null value. Right now I have one Users table with common fields and two other tables (Teachers and Students) to which I have setup a polymorphic relationship from user. My question is if this is a good approach, or if there are other ways to handle this more elegantly?

推荐答案

我将为教师创建1个表,为学生创建1个表,而不使用Users表/模型.这样,您可以将他们完全分开,而不必担心将来添加更多类型的用户.不断尝试使新用户适合您现有的用户模型(将被共享)是一件令人头疼的事情.开始时我犯了同样的错误,最终不得不重做该项目.

I would create 1 table for Teachers and 1 table for Students and not use the Users table/model. This way you can keep them completely separate and not worry about adding more types of users in the future. Continually trying to fit new users into your existing Users model, which would be shared, is a headache. I made this same mistake when I started and eventually had to rework the project.

有很多关于Laravel多认证/多用户在线的指南. 以下是一些可以帮助您入门的信息:

There are plenty of guides for Laravel multi-auth / multi-user online. Here are a couple to help you get started:

  • https://medium.com/hello-laravel/multiple-authentication-system-laravel-5-4-ac94c759638a
  • https://www.codementor.io/okoroaforchukwuemeka/9-tips-to-set-up-multiple-authentication-in-laravel-ak3gtwjvt

此外,在某些情况下,将用户模型用于多种类型的用户也很有意义.例如,对于大多数/所有字段都相同(而不是您的方案)的用户,您可能具有多个角色.在这种情况下,您可以为每个用户分配一个角色",并检查角色以进行操作(例如,添加中间件以防止角色访问各种路由).这是一个示例:

Also, there are cases where it makes sense to use the User model for multiple types of users. For example, you may have multiple roles for a user where most/all of the fields are the same (not your scenario). In this case, you can assign a 'role' to each User and the check the roles for actions (e.g. add middleware to prevent roles from accessing various routes). Here is an example:

由于您说的是老师和学生的实体非常不同,所以应该将它们分开.

Since you said the teacher and student entities are very different, you should keep them separate.

这篇关于Laravel:用于多种用户类型,多态关系的表结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆