2016-04-28 90 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