2015-09-28 108 views
2

我具有以下設置:Laravel 5.1口才ORM關係

Profile.php模型:

<?php 

namespace App\Models; 

use Illuminate\Database\Eloquent\Model; 

class Profile extends Model 
{ 

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

user.php的模型:

<?php namespace App\Models; 

use Illuminate\Auth\Authenticatable; 
use Illuminate\Database\Eloquent\Model; 
use Illuminate\Auth\Passwords\CanResetPassword; 
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; 
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract; 

class User extends Model implements AuthenticatableContract, CanResetPasswordContract 
{ 
    use Authenticatable, CanResetPassword; 

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

AuthController.php:

public function signup(Request $request) 
    { 
     $user = new User; 
     $profile = new Profile; 
     $user->email = $request->input('email'); 
     $user->first_name = $request->input('first_name'); 
     $user->last_name = $request->input('last_name'); 

     $user->password = Hash::make($request->input('password')); 

     $user->save(); 
     $role = Role::whereName('user')->first(); 

     $profile->city = $request->input('city'); ---> profile model 
     $profile->gender = $request->input('gender'); --> profile model 
     } 

如何保存至專業版基於關係的文件?由於外鍵約束,我無法直接保存到配置文件。

謝謝!

回答

3

您可以保存個人資料基礎上的關係:

public function signup(Request $request) 
{ 
    $user = new User; 
    $profile = new Profile; 
    $user->email = $request->input('email'); 
    $user->first_name = $request->input('first_name'); 
    $user->last_name = $request->input('last_name'); 

    $user->password = Hash::make($request->input('password')); 

    $user->save(); 
    $role = Role::whereName('user')->first(); 

    $profile->city = $request->input('city'); ---> profile model 
    $profile->gender = $request->input('gender'); --> profile model 

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

}