2017-03-21 22 views
1

私はhasOne()でリンクされた3つのテーブルを持っています。 Profile.phpにリンクされたModeel User.php City.phpにリンクされたCountry.phpとProfile.phpにリンクされたProfile.php。laravelはどのようにリンクテーブルのIDの自動割り当てを行うのですか?

プロファイルテーブルにuser_id外部キーがあります。 Countrysテーブルには、profile_idの外部キーがあります。また、Citysテーブルにはprofile_idの外部キーがあります。

私はこの外部キーをユーザーIDで正しく入力する方法を教えてください。

今私はRegistersUsers.php

public function register(Request $request) 
{ 
    $this->validator($request->all())->validate(); 

    event(new Registered($user = $this->create($request->all()))); 

    $this->guard()->login($user); 

    $user_id = Auth::user()->id; 

    $profile = new Profile; 
    $profile->user_id = $user_id; 
    $profile->save(); 

    $country = new Country;   
    $country->profile_id = $user_id;   
    $country->save(); 

    $city = new City;   
    $city->profile_id = $user_id;   
    $city->save(); 


    return $this->registered($request, $user) 
        ?: redirect($this->redirectPath()); 
} 

でそうしかし、私はより正確な方法があると思います。

ます。またとして save方法を使用することができます
$user = Auth::user(); 

$profile = $user->profile()->create(['name' => 'user_name']) 
// assumes relation name is profile 

$country = $profile->country()->create(['name' => 'country_name']); 
// assumes relation name is country 

$city = $profile->city()->create(['name' => 'city_name']); 
// assumes relation name is city 

あなたは create()を使用することができます
$user = Auth::user(); 

$profile = new Profile; 

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

$country = new Country; 

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

$city = new City; 

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

Docs

答えて

1

あなたは、この外部キーを埋めるautoに関係createメソッドを使用することができます関連するレコードを作成するための関係モデル:

public function register(Request $request) 
{ 
    $this->validator($request->all())->validate(); 

    event(new Registered($user = $this->create($request->all()))); 

    $this->guard()->login($user); 

    $user->profile()->create([ 
     'field' => 'value', // fields that are in the profiles table 
    ]); 

    $user->country()->create([ 
     'field' => 'value', // fields that are in the countries table 
    ]); 

    $user->city()->create([ 
     'field' => 'value', // fields that are in the cities table 
    ]); 

    return $this->registered($request, $user) 
     ?: redirect($this->redirectPath()); 
} 

ユーザーモデル内のリレーションの名前は、city(), country(), profile()であることに注意してください。

関連する問題