我有两张桌子:users, users_parameters
。
关系如下:users.id = users_parameters.user_id
在模型User
中,我有:
public function parameters()
{
return $this->hasOne('App\UserParameters', 'user_id');
}
我尝试添加新用户,如:
$user = new User();
$user->password = "123";
$user->email = "user@example.com";
$user->parameters()->name = $request->name;
$user->save(); // or ->push();
它不起作用,不要将新用户添加到相关表格。
答案 0 :(得分:4)
试试这个:
$user = new User();
$user->password = "123";
$user->email = "user@mail.ru";
$user->save();
$parameter = new Parameter();
$parameter->name = $request->name;
$parameter->save();
$user->parameters()->save($parameter);
或使用mass assignment:
$user = User::create(['name' => '123', 'email' => 'user@mail.ru']);
$user->parameters()->create(['name' => $request->name]);