在Laravel中保存相关记录

时间:2014-06-25 19:14:42

标签: laravel-4

我试图将两个记录关联起来,但它没有工作。

我这样做的方法(在存储库中)看起来像:

public function create(array $data)
{
    // Create the user
    $user = $this->userModel->create([
        'username' => $data['username'],
        'email'    => $data['email'],
        'password' => $data['password']
    ]);

    // Create the profile
    $profile = $this->profileModel->create([
        'location' => $data['profile']['location'],
        'bio'      => $data['profile']['bio']
    ]);

    $user->profile()->associate($profile);

    $user->save();

    return true;
}

(完整的来源可以在这里找到:https://github.com/LimeBlast/prijs/blob/master/app/Prijs/Repository/User/EloquentUser.php#L44

但是我收到了错误:"调用未定义的方法Illuminate \ Database \ Query \ Builder :: associate()"

我做错了什么?谢谢。

1 个答案:

答案 0 :(得分:1)

尝试

$profile->user()->associate($user);
$profile->save();

这是我最好的猜测。您需要在具有belongsTo方法

的对象上调用该关联