2017-12-27 240 views
2

我有一個用戶和父子關係中的用戶和角色模型,如下面的代碼所示。會發生什麼是我可以通過父母訪問孩子,但反之亦然。訪問孩子的角色($ user-> role)只給我這個ID。角色列在角色表上有一個外鍵,但反過來不起作用。 基本上, $角色包含所有用戶 $用戶>角色不會顯示用戶的角色,只是他的身份證雄辯模型的關係不起作用;甚至沒有查詢

Laravel-Debugbar還表明,用戶不執行額外的查詢,而角色一樣。

用戶表

id name email password remember_token client role created_at updated_at

角色表

id name display_name description created_at updated_at

用戶模型

namespace App; 
use Illuminate\Notifications\Notifiable; 
use Illuminate\Foundation\Auth\User as Authenticatable; 
use Illuminate\Database\Eloquent\Model; 
use Laratrust\Traits\LaratrustUserTrait; 
use App\Client; 
use App\Role; 
use App\Permission; 

class User extends Authenticatable 
{ 
    use LaratrustUserTrait; 
    use Notifiable; 

    protected $fillable = [ 
     'name', 'email', 'password','role', 
    ]; 
    public function client(){ 
     return $this->hasOne('App\Client', 'client'); 
    } 
    public function role(){ 
     return $this->belongsTo('App\Role')->withDefault(); 
    } 
} 

角色模型

namespace App; 

use Laratrust\Models\LaratrustRole; 
use App\Permission; 
use App\User; 

class Role extends LaratrustRole 
{ 
      protected $fillable = [ 
     'name', 'display_name', 'description', 
    ]; 
     public function GetHasPermission($perm){ 
      return DB::table('permission_role')->where('role', $this->id) 
        ->where('permission',$perm)->first()->value('type'); 
     } 
     public function users(){ 
      return $this->hasMany('App\User','role', 'id'); 
     } 
     public function permissions(){ 
      return $this->hasMany('App\Permission'); 
     } 
     public function getName(){ 
      return $this->name; 
     } 
} 

編輯:應該指出,我正在使用Laratrust。

回答

3

由於您未遵循Laravel naming conventions,您需要手動定義外鍵。因此,改變role()關係:

public function role() 
{ 
    return $this->belongsTo('App\Role', 'role')->withDefault(); 
} 

https://laravel.com/docs/5.5/eloquent-relationships#one-to-many-inverse

然後用->role()->first()代替->role->role()直接使用關係。 ->role首先嚐試使用對象的屬性,如果它不存在,它將加載相關數據(對象或集合)。由於User對象具有角色屬性,因此Laravel使用它而不是加載相關的Role對象。

+1

沒錯。 Laravel正在尋找一個role_id而不是角色 –

+0

已經嘗試過了;即使它應該是正確的,也不起作用。 –

+0

@ Statharas.903我很確定代碼是正確的。如果你需要幫助,請告訴我你的代碼有什麼錯誤。 –