【问题标题】:How in laravel do the automatic assignment of id in linked tables?laravel如何在链接表中自动分配id?
【发布时间】:2017-03-21 18:43:54
【问题描述】:

我有 3 个表与 hasOne() 链接。模型 User.php 与 Profile.php 链接 Profile.php 与 Country.php 链接,Profile.php 与 City.php 链接。

在 Profiles 表中有 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());
}

但我认为有一种更正确的方法。

【问题讨论】:

    标签: laravel-5


    【解决方案1】:

    您可以使用关系create 方法自动将此外键填充为:

    $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
    

    您也可以将save 方法用作:

    $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

    【讨论】:

      【解决方案2】:

      您可以使用hasOne 关系的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());
      }
      

      请注意,您在 User 模型中的关系名称假定为 city(), country(), profile()

      【讨论】:

        猜你喜欢
        • 2014-04-15
        • 1970-01-01
        • 2021-11-26
        • 2018-12-03
        • 2011-06-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多