【发布时间】:2020-08-06 01:28:26
【问题描述】:
用户有个人资料设置。我希望用户更改要更新的某些字段。但我创建了一个新列,应该更新。也许有人做得不对。请帮忙。非常感谢。
控制器
public function profile_settings_post(Request $request){
// Auth Specialist
$user = Auth::user();
// Data Specialist Validate
$data = $request->validate([
'first_name' => 'nullable|string',
'last_name' => 'nullable|string',
'phone_number' => 'nullable|integer',
'gender' => 'nullable',
'date_of_birth' => 'nullable',
'about_me' => 'nullable',
'address' => 'nullable',
'city' => 'nullable|string',
'country' => 'nullable|string',
'postal_code' => 'nullable|integer',
]);
$profile = $user->profile_settings()->updateOrCreate($data);
$profile->save();
// RETURN REDIRECT PROFILE SETTINGS INDEX
return redirect()->route('frontend.specialist.profile.settings');
}
用户模型
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public static function countPercent($count, $maxCount){
//one percent
$one_percent = $maxCount / 100;
// $count how much is percent
$percent = $count / $one_percent;
return $percent;
}
// 1 User have 1 profile settings (ONE TO ONE)
public function profile_settings(){
return $this->hasOne(Profile_Settings::class);
}
}
Profile_Settings 模型:
class Profile_Settings extends Model
{
// Fill in db
protected $fillable = [
'first_name', 'last_name', 'phone_number',
'gender', 'date_of_birth', 'about_me',
'address', 'city', 'country', 'postal_code',
];
// Profile settigns model belongs to User
public function user(){
return $this->belongsTo(User::class);
}
}
当我编辑某种字段时。在数据库中创建一个新字段
配置文件设置数据库不工作更新创建新列
【问题讨论】:
-
如果我理解正确,在更新配置文件设置时,您将使用更新的数据创建新记录,而不是使用更新的数据更新旧记录,因此您最终会得到两条旧记录/未更新)-(新/更新)对吗?
-
删除
$profile->save();行。updateOrCreate()已经将数据保存到数据库中。