Laravel - 创建具有 belongsTo 关系的对象

Laravel - create object with belongsTo relationship

我正在使用 Laravel 5.2 并且我已将一个用户组关联到具有 belongsTo 关系的任何用户。现在我想创建具有正确关系的用户。有没有可能把正确的关系带入create方法?

例如,我当前的代码在创建后更新对象:

$usergroup = Usergroup::findOrFail($usergroupId);

$user = User::create([
        'email' => $request->email,
        'password' => bcrypt($request->password) ]);
$user->usergroup()->associate($usergroup);
$user->save();

它有效,但不是一个很好的解决方案。我尝试了一些东西,但 none 奏效了。我想要这样的东西:

$usergroup = Usergroup::findOrFail($usergroupId);

$user = User::create([
        'email' => $request->email,
        'password' => bcrypt($request->password)
        'usergroup' => $usergroup ]); // does not work!

是的,只需将相关模型的id保存到外键字段即可:

$user = User::create([
    'email' => $request->email,
    'password' => bcrypt($request->password),
    'usergroup_id' => $usergroupId // or whatever it is
]);