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]);
你想为每个用户插入一个团队,或者只是拾取一个团队并将用户附加到该团队ID? – zorx
@zorx在这种情况下,它实际上是创建一个新团队 – Ash