所以我尝试使用Laravel4从单个表单中将值插入到两个表中。 这是我的Store()函数。我做得对..? 我知道我应该使用两个控制器AddressController.php和PeopleController.php ..但是我可以使用单个控制器使用单个表单插入两个表。?
public function store()
{
$rules = array(
'address_id' => 'required',
'contact_id' => 'required',
'prefix' => 'required',
'firstname' => 'required',
'middlename' => 'required',
'lastname' => 'required',
'suffix' => 'required',
'occupation' => 'required',
'gender' => 'required',
'comment' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
$user= Auth::user();
if (!empty($user->id))
$user_id=$user->id;
// process the login
/*if ($validator->fails()) {
return Redirect::to('people/create')
->withErrors($validator);
} else {*/
// store
$person = new Person;
$person->user_id=$user_id;
$person->address_id =Input::get('address_id');
//$person->contact_id = Input::get('contact_id');
$person->prefix = Input::get('prefix');
$person->firstname =Input::get('firstname');
$person->middlename =Input::get('middlename');
$person->lastname =Input::get('lastname');
$person->suffix =Input::get('suffix');
$person->occupation =Input::get('occupation');
$person->gender =Input::get('gender');
$person->comment =Input::get('comment');
//$person->user_id =Input::get('user_id');
$person->save();
$validator = Validator::make($data = Input::all(), Address::$rules);
$address->address1 = Input::get('address1');
$address->address2 = Input::get('address2');
$address->apt = Input::get('apt');
$address->city = Input::get('city');
$address->state = Input::get('state');
$address->zip = Input::get('zip');
$address->country = Input::get('country');
$address->save();
// redirect
Session::flash('message', 'Successfully created new Employee!');
//return Redirect::to('addresses/create');
return Response::json($person);
}
答案 0 :(得分:0)
只要您定义了人物和地址模型之间的关系,就可以使用人物模型的push()方法,该方法旨在一步保存多个相关模型
请注意,如果您为模型定义了fillable
,那么您也可以从代码中删除许多样板$person->prefix = Input::get('prefix');
语句