2016-03-06 88 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'。