2016-04-13 25 views
0

我有一個名爲的用戶配置文件。在配置文件表中有一列名爲userID.Now我想這列取值從用戶表的id。我已經完成數據庫關係的一部分。根據我的問題找到了滿意的答案。如何從用戶表中檢索用戶ID?

通過Laravel.I我是新的方式,到目前爲止已經試過

用戶模型:

class User extends Authenticatable 
{ 
    /** 
    * The attributes that are mass assignable. 
    * 
    * @var array 
    */ 
    protected $table ="users"; 
    protected $fillable = [ 
     'userName', 'email', 'password', 
    ]; 

    /** 
    * The attributes that should be hidden for arrays. 
    * 
    * @var array 
    */ 
    protected $hidden = [ 
     'password', 'remember_token', 
    ]; 

    public function userProfile(){ 
     return $this->hasOne('App\Profile'); 
    } 
} 

簡介型號:

class Profile extends Model 
{ 
    // 
    protected $table = "profiles"; 
    public $fillable = ["firstName","lastName","middleName","DOB","gender","featuredProfile","email","phone","summary","profilePic"]; 

    public function user(){ 
     return $this->belongsTo('App\User'); 
    } 
} 

,我試圖檢索userID{{$profile->userID}}。我真的不知道在哪裏是公關會徽和如何做到這一點?

回答

2

你需要告訴laravel得到的關係模型這樣

$profile = Profile::find(1); 
$userID = $profile->user->id; 

編輯: 從docs

模型自動假設有一個USER_ID外鍵。

而你的情況是這樣userId改變你hasOnebelongsTo方法告訴laravel的foreign_key名稱使用的是

public function profile() 
{ 
    return $this->hasOne('App\Profile', 'userId'); 
} 

public function user() 
{ 
    return $this->belongsTo('App\User', 'userId'); 
} 
+0

它給了我一個錯誤'試圖獲得非對象的屬性。 –

+0

'$ profile-> user-> id;'因爲'user'表的db列是'id'而不是'userid' – Junaid

0

請用戶ID添加到配置文件的可填充陣列。

請檢查下面的示例代碼是否也這樣做。

public $fillable = ["firstName","lastName","middleName","DOB","gender","featuredProfile","email","phone","summary","profilePic","userID"]; 
+0

這根本沒有必要。它甚至存在安全風險。由於他使用的不是user_id,而只是告訴laravel用戶表中id的名稱。 – Christophvh