2017-01-20 133 views
0

我想使用的用戶表的外鍵即user_types_id獲取用戶的類型,但是當我這樣做,我只是得到null並不能進入功能userTypeUser Model。任何幫助將非常感激。Laravel關係返回null外鍵

預先感謝您。我已經提供了相關的模型和表

控制器

public function dashboard() { 

    $userType = UserType::all(); 

    $id = Auth::user()->id; 
    var_dump($id); // returns id 

    $users = User::find($id); 
    var_dump($user->user_types_id); // returns user_type_id in users table 

     if($users->userType){ 
      var_dump($users->userType->types); // error is in here. Not taking userType. 
     } else { 
      echo 'does not exit'; 
     } 

     die(); 

    return view('dashboard', compact('users')); 
} 

用戶模型

<?php 
    namespace App; 

    use Illuminate\Foundation\Auth\User as Authenticatable; 
    use App\UserType; 

    class User extends Authenticatable 
    { 
     /** 
      * The attributes that are mass assignable. 
      * 
      * @var array 
      */ 

     protected $fillable = [ 
      'username', 'password', 
     ]; 

     /** 
      * The attributes that should be hidden for arrays. 
      * 
      * @var array 
      */ 

     protected $hidden = [ 
     'password', 'remember_token', 
     ]; 

     public function userType() { 
      return $this->belongsTo(UserType::class); 
     } 
    } 

用戶類型型號

<?php 

    namespace App; 
    use Illuminate\Database\Eloquent\Model; 
    use App\User; 

    class UserType extends Model 
    { 
     protected $fillable=['types']; 

    public function users() { 
     return $this->hasMany(User::class); 
     } 
    } 

用戶表

public function up() 
    { 
     Schema::create('users', function (Blueprint $table) { 
      $table->increments('id'); 
      $table->integer('user_types_id')->unsigned()->index(); 
      $table->string('username')->unique(); 
      $table->string('password'); 
      $table->string('salt'); 
      $table->rememberToken(); 
      $table->timestamps(); 
     }); 
    } 

用戶類型表

public function up() 
    { 
     Schema::create('user_types', function (Blueprint $table) { 
      $table->increments('id'); 
      $table->string('types'); 
      $table->timestamps(); 
     }); 
    } 

回答

3

你叫你們的關係USERTYPE,療法efore Eloquent假設外鍵被稱爲user_type_id,而不是user_types_id

更換

return $this->belongsTo(UserType::class); 

return $this->belongsTo(UserType::class, 'user_types_id'); 

告訴雄辯外鍵列的名稱,它應該工作。

+0

它確實爲我工作...非常感謝你的幫助... :)哦好吧...我的壞... –

+1

雄辯如果你不提供它們,會對關鍵名稱做出一些假設明確地。它假定主鍵被稱爲「id」,它也從關係名稱派生外鍵。 –

+0

雅我知道了......在外鍵上不應該有那個「s」......這是我身邊這個愚蠢的錯誤,但是謝謝你...... :) –