【问题标题】:How do I insert multiple joined models in Laravel 5如何在 Laravel 5 中插入多个连接模型
【发布时间】:2016-04-28 14:48:46
【问题描述】:

我正在尝试将示例用户插入到我的数据库中。

我的数据库包含 3 个模型,这些模型应该同时填充。这些模型是:用户、配置文件和团队。

  • 每个用户都有一个个人资料(一对一关系)。
  • 每个用户都可以 成为多个团队的一部分,每个团队可以有多个用户(多对多 关系)。

我的模型使用相关的belongsTo() / hasMany() 参考等正确设置。

在 laravel 中,我的代码如下所示:

$user =     new User([ 'email' => 'sample@sample.com', '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' => 'sample@sample.com', '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]);

【问题讨论】:

  • 您想为每个用户插入创建一个团队,还是只选择一个团队并将用户附加到这个 teamId ?
  • @zorx 在这种情况下,实际上是创建一个新团队

标签: php database laravel eloquent


【解决方案1】:

在您的示例中,您实际上永远不会持久化 User 模型。

在保存个人资料关系之前添加$user->save();

在将 $team 附加到 User 之前,您还需要保留它

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2014-08-09
    • 1970-01-01
    • 2015-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多