创建包含关系的 Eloquent 对象

Creating an Eloquent Object with relation included

我对 opps 很陌生,laravel 因此,要将这些值插入到具有 OneToOne 关系的 usersprofiles table 中,这是我的 store() 方法的样子

public function store(Requests\StoreNewUser $request)
{
    // crate an objct of user model
        $user = new \App\User;
        // now request and assign validated input to array of column names in user table
        $user->first_name = $request->input('first_name');
        $user->last_name = $request->input('last_name');
        $user->email = $request->input('email');
        $user->password = $request->input('password');
        /* want to assign request input to profile table's columns in one go 
        */
        $user->profile()->user_id = $user->id; // foreign key in profiles table
        $user->profile()->mobile_no = $request->input('mobile'); 
        dd($user); // nothing related to profile is returned
}

我正在创建新记录,因此 dd() 从来没有 returns 任何与个人资料相关的东西 table。

这是因为 $user 对象默认不包含关系吗? 如果是,我可以创建包含 User 模型中关联关系的 $user 对象吗?

或者我是否必须为每个 table 和 save() 数据创建两个单独的对象
但是 push() 方法的意义是什么?

编辑 1 P.S。是的,关系已经在 User & Profile 模型

中定义

这是因为 $user 对象默认不包含关系吗?如果是,我可以创建包含用户模型中关联关系的 $user 对象吗?

是的,您应该创建关系,默认不包括它们。

在您的 User 模型中,您想做这样的事情:

public function profile()
{
    return $this->hasOne('App\Profile'); // or whatever your namespace is
}

这还需要您创建一个 Profile 模型。

这肯定会回答您有关插入相关模型的问题:http://laravel.com/docs/5.1/eloquent-relationships#inserting-related-models

正如 The Alpha 提到的,你也没有做到,我认为你需要先保存你的用户模型,然后你可以通过关系添加。

您可以尝试以下操作。首先像这样保存父模型:

$user = new \App\User;
$user->first_name = $request->input('first_name');
// ...

$user->save();

然后使用如下方式创建并保存相关模型:

$profile = new \App\Profile(['mobile_no' => $request->input('mobile')]);
$user->profile()->save($profile);

还要确保您已经在 User 模型中创建了 profile 方法:

public function profile()
{
    return $this->hasOne('App\Profile');
}

我想我会更新这个答案并使其适用于 Laravel 5 以后的版本。我将使用@The Alpha 答案作为基础。

$profile = new \App\Profile(['mobile_no' => $request->input('mobile')]);
$user->profile()->associate($profile); // You can no longer call 'save' here
$user->profile()->save();

原因是您不能再在 belongsTo 关系(或任何其他关系)上调用 save,现在 returns 是 Illuminate\Database\Query\Builder 的一个实例。

现在最简单的方法是在您的用户 Class 文件上:

public function profile()
{
    return $this->hasOne(App\Profile::class);
}

并在您的用户控制器中使用以下存储方法:

public function store(Requests\StoreNewUser $request)
{
    $user = App\User::create(
        $request->only(
            [
                'first_name',
                'last_name',
                'email'
            ]
        )
    );

    $user->password = Illuminate\Support\Facades\Hash::make($request->password);
    //or $user->password = bcrypt($request->password);

    $user->profile()->create(
        [
            'mobile_no' =>  $request->mobile;
        ]
    );

    dd($user);
}

我不知道你是将纯文本密码保存到你的数据库还是在密码属性上使用了一个修改器,无论如何我认为上面的建议是一个很好的做法