不同的用户类型laravel [英] Different user types laravel
问题描述
我对laravel-5还是很陌生,到目前为止,我还是很喜欢它,但是在我从事我的项目时,我就遇到了这个疑问.
I'm fairly new to laravel-5 and I love it so far, but I've come out with this doubt while I was working on my project.
在我的应用中,我希望使用不同的用户类型,例如Employee,Admin和Freelance.当然,每种类型都有不同的权限,不同的页面访问权限.由于每种用户类型都有不同的数据,因此我为架构,管理员,员工和自由职业者创建了3个其他表,并在用户默认表上添加了一个user_type字段,以将其链接到也具有user_type的新表,从而使我默认用户表越小越好,只需登录信息即可.
In my app I want different user types, let's say Employee, Admin and Freelance. Every type will have ofcourse, different permissions and acces to pages. Since every user type has different data, I created 3 additional tables to my schema, admins, employees and freelancers, and added a field user_type on the users default table, to link it to the new tables, which have a user_type aswell, keeping my default users table small as possible, just login info.
所以我开始阅读,并雄辩地提出了多态关系,这显然正是我想要的.在实现了这些模型之间的关系和迁移之后,我不知道如何继续前进,不知道如何检查用户是自由职业者,管理员还是员工,以及如何为有关用户类型的某些页面提供权限.
So I started reading around and I came up with polymorphic relationship on eloquent, which apparently is exactly what I wanted. After implementing those models relationships and migrations, I don't know how to keep moving, and how to check if a user is either freelancer, admin or employee and how to give acces to certain page regarding the usertype.
这是我的用户模型的样子:
This is how my User Model looks like:
public function userable()
{
return $this->morphTo();
}
这是孩子们的样子:
public function user()
{
return $this->morphOne('User', 'userable');
}
推荐答案
由于您的User
模型是userable
,这意味着users
表应该具有多态关系所需的两列:userable_id
和userable_type
. userable_type
将包含拥有模型的类名(在您的情况下为Admin
,Freelancer
或Employee
).因此,这将返回用户类型类:
Since your User
model is userable
, that means the users
table should have the two columns necessary for polymorphic relations: userable_id
and userable_type
. The userable_type
will contain the class name of the owning model (which in your case will be either Admin
, Freelancer
or Employee
). So this will return the user type class:
User::find($id)->userable_type; // Use this to identify the user type
尽管通过将信息分成不同的表并使用多态关系来处理它们来规范化数据库结构是非常好的,但是我强烈建议您在单独的结构中处理角色. Entrust 软件包是一种非常好的方法,因为它允许使用非常健壮的方式来处理用户角色和权限.
While normalizing the database structure by separating information into different tables and using a polymorphic relation to handle them is very good, I strongly suggest you handle roles in a separate structure. The Entrust package is a very good way of doing that, because it allows for a very robust way of handling user roles and permissions.
这篇关于不同的用户类型laravel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!