2017-08-02 52 views
0

我對laravel比較新,並且需要一些手動配置的項目。Laravel用戶認證腳手架 - >將數據保存到兩個表中

背景:

  • 與認證腳手架工作(處理用戶 註冊和登錄)
  • 我有兩個表:簡介和用戶。
  • 所有用戶都有一個配置文件。
  • 但並非所有配置文件都有用戶。

設置: 資料表 => ID,名稱,化身等 用戶表 => PROFILE_ID,電子郵件,密碼

由於Laravel驗證(支架)處理登記和登錄。我正在嘗試在保存用戶表之前將數據保存到配置文件表中。

protected function create(array $data) 
{ 

    $profile = Profile::create 
    ([ 
     'slug' => $data['name'], 
     'name' => $data['name'], 
    ]); 

    $user = User::create 
    ([ 
     'profile_id' => $profile->id, 
     'name' => $data['name'], 
     'email' => $data['email'], 
     'password' => bcrypt($data['password']), 
    ]); 

    return $user; 
} 

但是這不起作用。錯誤消息告訴我在查詢中沒有分配profile_id。

我在做什麼錯?

回答

0

您的模型如何設置?如果雄辯和您的數據庫設置正確,你可以這樣做:

$profile = new Profile; 
$profile->slug = $data['name']; 
$profile->name = $data['name']; 

$profile->save(); 
// At this point now you'll be able to get an ID of the profile 

$user = new User; 
$user->profile_id = $profile->id; 
$user->name = $data['name']; 
$user->email = $data['email']; 
$user->password = bcrypt($data['password']); 

$user->save(); 

return $user; 
+0

是的,那是我最初的想法,但我得到以下幾點:SQLSTATE [HY000]:常規錯誤:1364字段「PROFILE_ID」沒有一個默認值(SQL:插入'users'('name','email','password','updated_at','created_at')值(John,[email protected],$ 2y $ 10 $ NoMoLSL1Sgek4enF2k2x7eL2Yo.To8O5uiriCrZdZk9rlW4CVbK1u, 2017-08-02 18:08:17,2017-08-02 18:08:17)) –

+0

檢查你的數據庫遷移,你需要確保你的配置文件ID列設置爲**自動增加** –

相關問題