简体   繁体   English

Laravel 5:保存相关模型时没有外键

[英]Laravel 5: no foreign key when saving related models

I have a simple one-to-one relationship between a User and a Profile, I'm trying to create a user and save their profile with the foreign key in one go and avoid having to pass the primary key and do two save() calls.我在用户和个人资料之间有一个简单的一对一关系,我正在尝试创建一个用户并一次性使用外键保存他们的个人资料,避免传递主键并执行两次save()调用。

Laravel will try to insert the corresponding Profile values without the id pointing back to the user. Laravel 将尝试插入相应的 Profile 值,而不会将 id 指向用户。 What am I doing wrong ?我究竟做错了什么 ?

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


class Profile extends Model
{
    protected $table = 'user_profile';

    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

class UserController extends Controller
{

  public function create(Request $request)
  {

    $this->validate($request, [
    ...
    ]) ;

    $user = new User() ;
    $profile = new Profile() ;

    $user->name = $request->input('name') ; 
    ...

    $profile->first_name = $request->input('first_name') ;
    $profile->last_name = $request->input('last_name') ;
    ...

    $user->profile()->save($profile) ;
    // $profile->user()->save($user) ; // doesn't work

    // $profile->user()->associate($user) ; // doesn't work
    // $profile->save() ;    
  }
}

you need first to save the user您首先需要保存用户

$user = new User;

$user->name = $request->input('name') ; 

$user->save();

$profile = new Profile;

$profile->first_name = $request->input('first_name') ;

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

The function name you are looking is "associate"您正在查找的函数名称是“关联”

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

$user->save();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM