Laravel-创建具有属于关系的对象


Laravel - create object with belongsTo relationship

我正在使用Laravel 5.2,并且我已经将用户组与具有belongsTo关系的任何用户相关联。现在,我想创建具有正确关系的用户。是否有可能将正确的关系带入创建方法?

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

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

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

$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
]);