2017-04-21 106 views
0

我有4個表:laravel關係的表

用戶(ID,ROLE_ID)

角色(ID)

permission_role(ROLE_ID,permission_id)

許可(ID,姓名)

用戶模型

<?php 

namespace App; 

use Illuminate\Notifications\Notifiable; 
use Illuminate\Foundation\Auth\User as Authenticatable; 
use Zizaco\Entrust\Traits\EntrustUserTrait; 

class User extends Authenticatable 
{ 
    use Notifiable; 
    use EntrustUserTrait; 

    /** 
    * The attributes that are mass assignable. 
    * 
    * @var array 
    */ 
    protected $fillable = [ 
     'name', 'email', 'password', 
    ]; 

    /** 
    * The attributes that should be hidden for arrays. 
    * 
    * @var array 
    */ 
    protected $hidden = [ 
     'password', 'remember_token', 
    ]; 
    public function roles() 
{ 
    return $this->hasOne('App\Role', 'id', 'role_id'); 
} 
} 

榜樣

<?php 

namespace App; 

use Illuminate\Database\Eloquent\Model; 
use Zizaco\Entrust\EntrustRole; 

class Role extends EntrustRole 
{ 
    public function users() 
{ 
    return $this->belongsTo('App\User','role_id','id'); 
} 
public function permissions() 
    { 
     return $this->belongsToMany('App\Permission','permission_role'); 
    } 
} 

權限模型:

<?php 

namespace App; 

use Illuminate\Database\Eloquent\Model; 
use Zizaco\Entrust\EntrustPermission; 

class Permission extends EntrustPermission 
{ 
    public function roles() 
    { 
     return $this->belongsToMany('App\Role','permission_role'); 
    } 
} 

,我想在我的控制器進行測試,看是否通過用戶如果條件有權限delete_article,任何幫助嗎?並感謝

回答

0

在你角色模型 像這樣的事情,你需要做的(多對多)

//....................... 
public function permissions() 
{ 
    return $this->belongsToMany('App\Permission','permission_role''role_id', 'permission_id'); 
} 
//...................... 

多對多關係:Link

並獲取數據進入你的控制器

//.......................................... 
$user = get data with role and permission 
$roles= $user->roles; 
foreach($roles as $role){ 
    foreach($role->permissions as $permission){ 
     $permissiona_name = $permission->name; 
    } 
} 
//........................... 

用的var_dump($用戶)首先檢查

Many to many with pivot(見Retrieving Intermediate Table Columns部分)

return $this->belongsToMany('App\Role')->withPivot('column1', 'column2'); 

參見 「Has Many Through