如何使用惰性关系在Laravel中的相关表中保存数据?

时间:2016-10-22 13:19:16

标签: laravel laravel-5 laravel-5.3

我有两张桌子: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();

它不起作用,不要将新用户添加到相关表格。

1 个答案:

答案 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);

Here's an explanation.

或使用mass assignment

$user = User::create(['name' => '123', 'email' => 'user@mail.ru']);
$user->parameters()->create(['name' => $request->name]);