如何在Laravel 5中建立用户和角色的关系
我有两张桌子:如何在Laravel 5中建立用户和角色的关系,laravel,laravel-5,eloquent,Laravel,Laravel 5,Eloquent,我有两张桌子: User -> id : name : role_id : ->references('id')->on('roles'); Roles -> id : role_name : access : 我正在尝试从用户访问角色详细信息 我的用户模型有: 公共功能角色() { 返回$this->belongsTo('App\Role'); } 我的榜样是: 公共函数用户() { 返回$this->hasMany('App\User
User ->
id :
name :
role_id : ->references('id')->on('roles');
Roles ->
id :
role_name :
access :
我正在尝试从用户访问角色详细信息
我的用户模型有:
公共功能角色()
{
返回$this->belongsTo('App\Role');
}
我的榜样是:
公共函数用户()
{
返回$this->hasMany('App\User');
}
当我尝试执行以下操作时:
$user=user::find(1);
$details=[
“名称”=>$user->first\u name,
'role'=>$user->role->role\u name
];
我得到一个错误:
正在尝试获取非对象的属性
“我的角色”表包含访问列,其中包含对不同路由的权限数组。因此,我的用户将只有一个角色。而一个角色可以有多个用户
如何做到这一点?对于关系,您不需要数据透视表,因此可以删除用户角色表。然后将role\u id
列添加到users
表中,该列将引用roles
表中的id
列。接下来,为每个模型定义如下关系:
//User.php
公共职能角色()
{
返回$this->belongsTo('App\Role');
}
及
//Role.php
公共功能用户()
{
返回$this->hasMany('App\User');
}
现在,您可以通过如下关系访问您的角色:
$user->role->name;
我注意到您没有使用laravel默认表命名约定,
您正在使用用户角色,其中laravel命名约定规定您应使用:
角色用户(字母和单数)
您可以通过声明资源的自定义表名来覆盖belongstomy
public function users() {
return $this->belongsToMany('App\User', 'user_roles');
}
在第二个节点上,也有一些很好的库来处理这类事情,请看:我遇到了问题,我在用户表中有一个角色列,所以当我这样做时
$user->role->role_name
它获取的是角色
列,而不是关系。在我最近的项目中,我以这种方式处理这些需求。。
首先,数据库表结构/迁移
用户表
角色表
角色和用户关系表
在这些表之后,您必须通过分配给特定角色来处理权限
许可
权限和角色表关系
最后,我们的模型看起来很像:
用户模型
榜样
权限模型
好的,这是帮助用Laravel5实现基本ACL和Auth的基本结构
如果您有任何进一步的相关问题,请告诉我。或者,如果您需要完整的实现,我会提供给您 它不起作用。我的用户将只有一个角色,那么多对多是多少?我推断您想要多对多,因为您有一个透视表,如果您想要一对多关系,这是没有用的。如果您想要一对多关系,请去掉user\u roles
表,并在users表中添加role\u id
列。这将允许您为每个用户指定一个角色。另外,当您应用我建议的更改时,哪些角色不起作用?错误消息是什么?我已更新我的答案以反映对您问题的更改。感谢您指出,我做了这些更改,但仍然出现相同的错误。我更新了我的问题,请再次查看。我现在正在学习,所以我现在宁愿远离库。你也可以使用$user->role()->role\u name
来区分关系和属性。我正在学习laravel,这是一个很好的观点+1 @HarryGeo@Sadar你能进一步解释一下吗?那么每个表中的典型值是什么?你能进一步解释一下吗?那么每个表中的典型值是什么?@Daniel well,user
用于用户相关信息,role
和permission
存储管理、订阅者等角色,permission是您在系统下获得的所有权限的列表,user具有角色,roles具有多个权限。因此,role\u user
用于查看用户角色关系,而permission\u role
用于检查每个角色访问的内容。
class CreateUserTable extends Migration {
public function up() {
Schema::create('user', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password', 60);
$table->boolean('status')->default(0);
$table->boolean('is_admin')->default(0);
$table->boolean('notify')->default(0);
$table->rememberToken();
$table->timestamps();
});
}
public function down() {
Schema::drop('user');
}
}
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateRoleTable extends Migration {
public function up()
{
Schema::create('role', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->string('display_name')->nullable();
$table->string('description')->nullable();
$table->boolean('status')->default(0);
$table->timestamps();
});
}
public function down()
{
Schema::drop('role');
}
}
class CreateRoleUserTable extends Migration {
public function up() {
// Create table for associating roles to users (Many-to-Many)
Schema::create('role_user', function (Blueprint $table) {
$table->integer('user_id')->unsigned();
$table->integer('role_id')->unsigned();
$table->foreign('user_id')->references('id')->on('user')
->onUpdate('cascade')->onDelete('cascade');
$table->foreign('role_id')->references('id')->on('role')
->onUpdate('cascade')->onDelete('cascade');
$table->primary(['user_id', 'role_id']);
});
}
public function down() {
Schema::drop('role_user');
}
}
class Permission extends Migration {
public function up() {
Schema::create('permission', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->string('pattern');
$table->string('target');
$table->string('module');
$table->string('display_name')->nullable();
$table->boolean('status')->default(0);
$table->timestamps();
});
}
public function down() {
Schema::drop('permission');
}
}
class PermissionRole extends Migration {
public function up() {
// Create table for associating roles to permission (Many-to-Many)
Schema::create('permission_role', function (Blueprint $table) {
$table->integer('permission_id')->unsigned();
$table->integer('role_id')->unsigned();
$table->foreign('permission_id')->references('id')->on('permission')
->onUpdate('cascade')->onDelete('cascade');
$table->foreign('role_id')->references('id')->on('role')
->onUpdate('cascade')->onDelete('cascade');
$table->primary(['permission_id', 'role_id']);
});
}
public function down() {
Schema::drop('permission_role');
}
}
namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract {
use Authenticatable, CanResetPassword;
protected $table = 'user';
protected $fillable = ['name', 'email', 'password', 'is_admin'];
protected $hidden = ['password', 'remember_token'];
public function scopeActive($query) {
return $query->whereStatus('1');
}
public function scopeAdmin($query) {
return $query->whereIsAdmin('1');
}
public function scopeNotify($query) {
return $query->whereNotify('1');
}
public function roles() {
return $this->belongsToMany('App\Role', 'role_user', 'user_id', 'role_id');
}
public function attachRole($role) {
if (is_object($role)) {
$role = $role->getKey();
}
if (is_array($role)) {
$role = $role['id'];
}
$this->roles()->attach($role);
}
public function detachRole($role) {
if (is_object($role)) {
$role = $role->getKey();
}
if (is_array($role)) {
$role = $role['id'];
}
$this->roles()->detach($role);
}
public function attachRoles($roles) {
foreach ($roles as $role) {
$this->attachRole($role);
}
}
public function detachRoles($roles) {
foreach ($roles as $role) {
$this->detachRole($role);
}
}
public function isSuperUser() {
return (bool)$this->is_admin;
}
public function hasAccess($permissions, $all = true) {
if ($this->isSuperUser()) {
return true;
}
return $this->hasPermission($permissions, $all);
}
public function hasPermission($permissions) {
$mergedPermissions = $this->getMergedPermissions();
//dd($mergedPermissions);
if (!is_array($permissions)) {
$permissions = (array)$permissions;
}
foreach ($permissions as $permission) {
$matched = false;
// We will set a flag now for whether this permission was
// matched at all.
$founded_perms = find_in($mergedPermissions, "name", $permission);
if (!empty($founded_perms)) {
$matched = true;
}
}
if ($matched === false) {
return false;
}
return true;
}
public function getMergedPermissions() {
$permissions = array();
foreach ($this->getRoles() as $group) {
$permissions = array_merge($permissions, $group->permissions()->get()->toArray());
}
return $permissions;
}
public function getRoles() {
$roles = [];
if ($this->roles()) {
$roles = $this->roles()->get();
}
return $roles;
}
}
namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model {
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'role';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['name', 'display_name', 'description'];
public function scopeActive($query) {
return $query->whereStatus('1');
}
/**
* Many-to-Many relations with User.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function users() {
return $this->belongsToMany('App\User');
}
public function permissions() {
return $this->belongsToMany("App\Permission");
}
}
namespace App;
use Illuminate\Database\Eloquent\Model;
class Permission extends Model {
protected $table = 'permission';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['name', 'pattern', 'target', 'module', 'display_name', 'status'];
public static function displayable() {
$prepared_array = [];
$temp = self::orderBy('module')->get()->toArray();
foreach ($temp as $sin) {
$prepared_array[$sin['module']][] = $sin;
}
return $prepared_array;
}
public function scopeActive($query) {
return $query->whereStatus('1');
}
public function roles() {
return $this->belongsToMany("App\Role");
}
}