Laravel:如何从一个模型访问变量到另一个模型

时间:2019-07-24 06:17:43

标签: laravel variables model access

我有两个模型,分别对应数据库中的两个表:ParticipantLookupModelEventParticipantModel。每当我在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
}

我知道这可能只是一个非常简单的问题。但任何帮助将不胜感激。谢谢!

1 个答案:

答案 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
}