【问题标题】:Laravel save with relationLaravel 保存关系
【发布时间】:2014-06-03 02:57:12
【问题描述】:

如何用关系保存新用户?

用户模型:

public function profile(){
    return $this->hasOne('Profile','id');
}

轮廓模型:

protected $table = 'users_personal';
public function user(){
    return $this->belongsTo('User','id');
}

主要功能:

            $u                      = new User;
            $u->username            = $i['username'];
            $u->email               = $i['mail'];
            $u->password            = Hash::make( $i['password'] );
            $u->type                = 0;
            $u->profile->id         = $u->id;
            $u->profile->name       = $i['name'];
            $u->profile->surname    = $i['surname'];
            $u->profile->address    = $i['address'];
            $u->profile->number     = $i['strnum'];
            $u->profile->city       = $i['city'];
            $u->profile->ptt        = $i['ptt'];
            $u->profile->mobile     = $i['mobile'];
            $u->profile->birthday   = $i['year'].'-'.$i['mob'].'-'.$i['dob'];
            $u->profile->newsletter = $i['news'];
            $u->push();

如果我这样做,我会收到错误:间接修改重载属性 User::$profile 无效

创建新用户时如何保存用户配置文件?

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    您应该创建您的 Profile 对象,然后将其附加到您的用户。

    $u                      = new User();
    $u->username            = $i['username'];
    $u->email               = $i['mail'];
    $u->password            = Hash::make( $i['password'] );
    $u->type                = 0;
    $u->save();
    
    $profile = new Profile();
    $profile->id         = $u->id;
    $profile->name       = $i['name'];
    $profile->surname    = $i['surname'];
    $profile->address    = $i['address'];
    $profile->number     = $i['strnum'];
    $profile->city       = $i['city'];
    $profile->ptt        = $i['ptt'];
    $profile->mobile     = $i['mobile'];
    $profile->birthday   = $i['year'].'-'.$i['mob'].'-'.$i['dob'];
    $profile->newsletter = $i['news'];
    
    $u->profile()->save($profile);
    

    【讨论】:

      【解决方案2】:
      $profile = new UserProfile( array( 
          'name' => $i['name'],
          'surname' => $i['surname'],
          // ...
      ) );
      
      $user = new User( array(
          'username' => $i['username'],
          // ...
      ) );
      
      $profile = $user->profile()->save($profile);
      

      更多信息请查看相关documentation entry

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-03-05
        • 2015-02-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多