我有两个模型,分别对应数据库中的两个表:ParticipantLookupModel
和EventParticipantModel
。每当我在event_participant_tbl
内添加一条记录时,都应先在participant_lookup_tbl
中添加记录,然后再添加到前一个记录中。因此,您可以将其视为父子关系。
这就是我的participant_lookup_tbl
(简而言之)的样子:
p_id | fName | lName | companyName
这就是我的event_participant_tbl
(简而言之)的样子:
p_id | p_id_fk
您已经知道我的p_id_fk
是一个外键,它引用了p_id
中的participant_lookup_tbl
。因此,每当我调用一个将记录插入participant_lookup_tbl
内的函数时,其最后插入的p_id
也必须作为一个值插入p_id_fk
中的event_participant_tbl
中。 / p>
在我的ParticipantLookupController
中:
public function store(Request $request) {
$this->validate($request, [
'fName' => 'required|string|max:191',
'lName' => 'required|string|max:191',
'compName' => 'required|string|max:191'
]);
$participant = ParticipantLookupModel::create($request->all());
$id = $participant->participant_id;
return ['message' => $id]; //test if it returns the correct id
}
我已成功返回正确的最后插入的p_id
。但是我不知道如何在我的EventParticipantController
内部访问它。
在我的EventParticipantController
中:
public function store(Request $request) {
//access $id from ParticipantLookupController and save
}
我知道这可能只是一个非常简单的问题。但任何帮助将不胜感激。谢谢!
答案 0 :(得分:0)
您是否需要转到另一个控制器?您可以使用 ParticipantLookupController
的相同方法进行操作public function store(Request $request) {
$this->validate($request, [
'fName' => 'required|string|max:191',
'lName' => 'required|string|max:191',
'compName' => 'required|string|max:191'
]);
$participant = ParticipantLookupModel::create($request->all());
return redirect()->action(
'EventParticipantController@store', ['id' => $participant->id]
);
}
在此更新的部分中,您需要使用 id 作为 EventParticipantController
的 store 方法的参数。public function store($id) {
//check $id exists and save or abort
}