私は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);