我有一個用戶模型和捐助者模型,其中包含捐助者類型的用戶的額外數據。當用戶想要更新他的個人資料時,我想同時更新這兩個表。下面是代碼:同時更新兩個模型(Laravel 4.2)
//用戶模型
public function donor() {
return $this->hasone('Donor','u_id');
}
//捐贈型號
public function user(){
return $this->belongsTo('User','id');
}
//控制器
public function updateProfile() {
$input = Input::all();
$lat = Input::get('latitude');
$lng = Input::get('longitude');
$rules = array('username' => 'required|unique:users');
$v = Validator::make($input, $rules);
$id = Auth::user()->id;
if ($v->fails()) {
return Redirect::to('donor/')->withErrors($v)->withInput(Input::all());
} else {
$user = User::find($id);
$donor = User::find($id)->donor;
$user->username = Input::get('username');
$user->name = Input::get('name');
$donor->name = Input::get('name');
$donor->ic = Input::get('ic');
$donor->gender = Input::get('gender');
$donor->blood_type = Input::get('blood_type');
$donor->race = Input::get('race');
$donor->religion = Input::get('religion');
$donor->state = Input::get('state');
$donor->address = Input::get('address');
$donor->lng = $lng;
$donor->lat = $lat;
$donor->email = Input::get('email');
$donor->phone = Input::get('phone');
$user->save();
$donor->save();
return View::make('donorProfile', array('message' => 'Profile successfully updated!'));
}
}
我試圖按照文檔和至今我去那兒。當提交bt而不是捐助者數據時,用戶數據被保存。
你有錯誤嗎?檢查laravel日誌。 – TheFallen
我在這裏得到錯誤$ donor = User :: find($ id) - >列ID的捐助者。 – user94743
好的,但是你能編輯你的文章並粘貼錯誤信息嗎? – TheFallen