我想在三個不同的表中同時添加插入數據。但是,一旦數據插入到第一個表中,我需要獲取該ID並繼續將該數據插入其他兩個表中。這些是申請表,語言表(每個申請人可能知道多種語言)和技能表(也是一個或多個)。將數據添加到多個表(laravel 4)
下面是我一直在努力代碼:
型號:
class Apply extends Eloquent {
protected $table = 'application';
protected $fillable = ['user_id', 'gender', 'dob', 'ic', 'marriage_status', 'phone', 'city', 'street', 'course', 'university',
'academic_degree', 'uni_start_date', 'uni_end_date', 'addinfo', 'working_company', 'position', 'start_date', 'end_date', 'reason'];
public function lang() {
return $this->hasMany('Lang');
}
}
class Lang extends Eloquent
{
protected $table = 'language';
public function apply(){
return $this->belongsTo('Apply');
}
}
class Skills extends Eloquent
{
protected $table = 'skills';
public function apply(){
return $this->belongsTo('Apply');
}
}
控制器:
public function createcv() {
$input = Input::all();
$rules = array('ic' => 'required',
'phone' => 'required',
'course' => 'required');
$v = Validator::make($input, $rules);
if ($v->passes()) {
$apply = Apply::create(array('user_id' => Auth::user()->id, 'gender' => $input['gender'],
'dob' => $input['dob'], 'ic' => $input['ic'], 'marriage_status' => $input['mstatus'],
'phone' => $input['phone'], 'city' => $input['city'], 'street' => $input['street'],
'course' => $input['course'], 'university' => $input['institution'],
'academic_degree' => $input['adegree'], 'uni_start_date' => $input['uni-startdate'],
'uni_end_date' => $input['uni-enddate'], 'addinfo' => $input['addinfo'],
'working_company' => $input['jobinstitution'], 'position' => $input['jobposition'],
'start_date' => $input['startdate'], 'end_date' => $input['enddate'], 'reason' => $input['reason']));
$apply->save();
$app_id = $apply->id;
$lang = Lang::create(array('app_id' => $app_id, 'lang' => $input['lang1'],
'reading' => $input['read1'], 'writing' => $input['write1'],
'speaking' => $input['speak1'], 'institution' => $input['inst1']
));
$lang->save();
$skills = Skills::create(array('app_id' => $app_id, 'prog_name' => $input['prog1'],
'level' => $input['level1'], 'institution' => $input['instprog1']));
$skills->save();
return Redirect::to('home');
} else {
return Redirect::to('create-cv')->withInput()->withErrors($v);
}
}
您的問題是什麼? –
@JoseRojas謝謝你的提問。我不知道如何在同一時間在三張表上添加數據。 –