亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在拉拉維爾中一對一地更新關系?

如何在拉拉維爾中一對一地更新關系?

PHP
哈士奇WWW 2022-09-25 19:06:39
在我的用戶模型中,我有以下代碼public function profile(){    return $this->hasOne(UserProfile::class);}在輪廓模型中,public function user(){   return $this->belongsTo(User::class);}create 方法正在工作,但是當我嘗試使用以下代碼更新配置文件時,它正在創建一個新的配置文件,并且不會更新配置文件信息。$profile = new UserProfile();$profile->dob = '1999-03-20';$profile->bio = 'A professional programmer.';$profile->facebook = 'http://facebook.com/test/1';$profile->github = 'http://github.com/test/1';$profile->twitter = 'http://twitter.com/test/1';$user = User::find($userId);$res = $user->profile()->save($profile);在一對一關系中更新的正確方法是什么?
查看完整描述

3 回答

?
一只萌萌小番薯

TA貢獻1795條經驗 獲得超7個贊

我使用推送方法修復了它。這是代碼。

$user = User::find($userId);

$user->name = "Alen";

$user->profile->dob = '1999-03-20';

$user->profile->bio = 'A professional programmer.';

$user->profile->facebook = 'http://facebook.com/test/1';

$user->profile->github = 'http://github.com/test/1';

$user->profile->twitter = 'http://twitter.com/test/1';

$user->push();


查看完整回答
反對 回復 2022-09-25
?
慕工程0101907

TA貢獻1887條經驗 獲得超5個贊

您正在使用保存方法來保存新記錄。使用更新查詢


//controller

$userObj=new User();

if(!empty($userId) && $userId!=null){

$userObj->updateByUserId($userId,[

'dob' = '1999-03-20';

'bio' = 'A professional programmer.';

'facebook' = 'http://facebook.com/test/1';

'github' = 'http://github.com/test/1';

'twitter' = 'http://twitter.com/test/1';

]);

}


//model

function updateByUserId($userId,$updateArray){

return $this->where('user_id',$userId)->update($updateArray);

}


查看完整回答
反對 回復 2022-09-25
?
慕斯709654

TA貢獻1840條經驗 獲得超5個贊

你做得很好,但我可以建議一點改進


您可以使用以下


$user = User::with('profile')->findOrFail($userId);


if ($user->profile === null)

{

    $profile = new UserProfile(['attr' => 'value', ....]);

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

}

else

{

    $user->profile()->update(['attr' => 'value', ....]);

}


查看完整回答
反對 回復 2022-09-25
  • 3 回答
  • 0 關注
  • 105 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號