Laravel与关系保存

时间:2014-06-02 18:37:54

标签: php laravel eloquent

如何通过关系保存新用户?

用户模型:

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无效

如何在创建新用户时保存用户个人资料?

2 个答案:

答案 0 :(得分:5)

您应该创建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);

答案 1 :(得分:0)

$profile = new UserProfile( array( 
    'name' => $i['name'],
    'surname' => $i['surname'],
    // ...
) );

$user = new User( array(
    'username' => $i['username'],
    // ...
) );

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

有关详细信息,请参阅相关的documentation entry