2016-03-06 89 views
1

我正尝试与2个模型UserRole创建一对多关系。所以,我希望那一个User只能有一个角色,并且Role可以被分配到多于User。我试图按照官方教程https://laravel.com/docs/5.1/eloquent-relationships#one-to-many,并结束了与此:一对多关系不起作用

class User extends Model 
{ 
    public function role() 
    { 
     return $this->belongsToMany('App\Admin\Role'); 
    } 
} 

class Role extends Model 
{ 

    protected $table = 'roles'; 

    public function users() 
    { 
     return $this->hasMany('App\Admin\User'); 
    } 

} 

基于该链接的,我觉得Role是同样的事情Post,一个Role可以分配给许多User。然而,这完全不是那么回事,这里就是我想对特定User

$role_first = $user->role; // Eloquent\Collection 
$role_second = $user->role(); // Eloquent\Relations\BelongsToMany 

$role_first->role_title // 'Undefined property: Illuminate\Database\Eloquent\Collection::$role_title' 
$role_second->role_title // exception 'ErrorException' with message 'Undefined property: Illuminate\Database\Eloquent\Relations\BelongsToMany::$role_title' 

访问角色名称究竟是什么错在这里?

回答

2

User

public function role() 
{ 
    // not $this->belongsToMany('App\Admin\Role'); 
    return $this->belongsTo('App\Admin\Role'); 
} 

因为你想有一个oneToMany没有manyToMany关系。

0

这应该做到这一点。请试试看

class User extends Model 
{ 
    public function role() 
    { 
     return $this->hasOne(App\Admin\Role::class); 
    } 
} 

// user belongs to one role 
class Role extends Model 
{ 

    protected $table = 'roles'; 

    public function users() 
    { 
     return $this->belongsTo(App\Admin\User::class); 
    } 

} 
+0

您在此处创建了一对一关系(hasOne和belongsTo),这是不正确的。许多用户可以具有相同的角色,这是一对多的关系。 –

0

用户模型

class User extends Authenticatable{ 

    public function roles(){ 
    return $this->belongsTo('App\Admin\Role'); 
    } 
    } 

角色模型

class Role extends Model{ 

    public function users(){ 
     return $this->hasMany('App\Admin\User'); 
    } 
     } 

用户只能有一个角色,角色可以分配给多个用户。

0

只需确保关系

  • A用户hasOne角色
  • 作用belongsToMany用户

所以,在这种情况下

class User extends Model 
{ 
    public function role() 
    { 
     return $this->hasOne('App\Admin\Role'); 
    } 
} 
class Role extends Model 
{ 

    protected $table = 'roles'; 

    public function users() 
    { 
     return $this->belongsToMany('App\Admin\User'); 
    } 
} 

和M在你的角色迁移表中检查你的user_id外部约束是'unsigned'。