简体   繁体   中英

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.

Laravel will try to insert the corresponding Profile values without the id pointing back to the user. 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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