簡體   English   中英

Laravel 用戶、角色、權限關系實現問題

[英]Laravel user, role, permission relationship implemention problem

我有三個模型UserRolePermission 這些模型與其表之間存在復雜但眾所周知的關系。

表格及其列:

用戶 角色 權限 許可角色
ID ID ID ID
... ... ... 角色編號
角色編號 ... ... permission_id

所以每個用戶只有一個角色,每個角色都有很多權限

<?php

class User
{


public function role()
{
    return $this->belongsTo(Role::class);
    
}

public function permissions()
{
    return $this->hasManyThrough(Permission::class,Role::class);
}
}


class Role
{


public function users()
{
    return $this->hasMany(User::class);
  
}

public function permissions()
{
    return $this->belongsToMany(Permission::class);
    
}
}


class Permission
{


public function roles()
{
    return $this->belongsToMany(Role::class);
    
}

public function users()
{
    return $this->hasManyThrough(User::class,Role::class);
}
}

我可以訪問

  1. $用戶->角色,
  2. $用戶->角色->權限,
  3. $角色->用戶,
  4. $角色->權限
  5. $權限->角色

除了

  1. $權限->用戶

返回 sql 錯誤:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'roles.permission_id' in 'field list' (SQL: select `users`.*, `roles`.`permission_id` as `laravel_through_key` from `users` inner join `roles` on `roles`.`id` = `users`.`role_id` where `roles`.`permission_id` = 1) 

但為什么?

你能試試這樣嗎:

允許
public function users()
{
    return $this->hasManyThrough(
        User::class,    // The model to access to
        PermissionRole::class,    // The intermediate table that connects the User with the Role.
        'permission_id',   // The column of the intermediate table that connects to this model by its ID.
        'role_id',    // The column of the intermediate table that connects the Role by its ID.
        'id',    // The column that connects this model with the intermediate model table.
        'role_id'   // The column of the Users table that ties it to the Roles. 
    );
}

我找到了這篇文章。

如果你與你的表格進行比較,它可能是這樣的:

  • audio_files表是你的users
  • podcast表是你的roles
  • subscription表是你的permission_role
  • users表是你的permissions

也許這令人困惑,但如果這有效,請告訴我。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM