laravel relationship'stable

时间:2017-04-21 23:25:04

标签: php laravel

我有4张桌子:

  

用户(ID,ROLE_ID)

     

作用(ID)

     

permission_role(ROLE_ID,permission_id)

     

权限(id,name)

用户模型

 <?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来条件,任何帮助?并谢谢

1 个答案:

答案 0 :(得分: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($ user)

Many to many with pivot(请参阅Retrieving Intermediate Table Columns部分)

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

另见&#34; Has Many Through&#34;