2016-04-28 84 views
0

我試圖將示例用戶插入到我的數據庫中。如何在Laravel 5中插入多個加入的模型

我的數據庫包含3個模型,這些模型都應該同時填充。這些模型是:用戶,配置文件和團隊。

  • 每個用戶有一個配置文件(一對一關係)。
  • 每個用戶可以將 作爲衆多團隊的一部分,每個團隊可以擁有多個用戶(多對多關係)。

我的模型是正確設置有關belongsTo()/hasMany()引用等

在laravel,我的代碼看起來是這樣的:

$user =  new User([ 'email' => '[email protected]', 'password' => bcrypt('password1'), 'username'=> 'sampleuser']); 
$profile = new Profile(['name' => 'Sample','bio' => 'All about me']); 
$team =  new Team(['name' => 'SuperAdmins']); 

$user->profile()->save($profile); 
$user->teams()->attach($team, ['type' => 4]); 

我怎樣才能得到這個工作>?這不起作用,當插入到配置文件表中時,我的控制檯引用了'user_id' cannot be null

編輯: 謝謝,從羅斯·威爾遜的答案,我去了:

$user =  new User([ 'email' => '[email protected]', 'password' => bcrypt('password1'), 'username'=> 'sampleuser']); 
    $user->save(); 

    $profile = new Profile(['name' => 'Sample','bio' => 'All about me']); 
    $user->profile()->save($profile); 

    $team =  new Team(['name' => 'SuperAdmins']); 
    $user->teams()->save($team, ['type' => 4]); 
+0

你想爲每個用戶插入一個團隊,或者只是拾取一個團隊並將用戶附加到該團隊ID? – zorx

+0

@zorx在這種情況下,它實際上是創建一個新團隊 – Ash

回答

1

你的榜樣,你從來沒有真正堅持的User模型。

在保存配置文件關係之前添加$user->save();

您還需要將其連接到User

希望這有助於之前堅持的$team