Search code examples
codeigniter-4

Codeigniter 4 saving inserted id from first table into second table


I am trying to save my data into 2 tables. I have 2 tables, teams and members. After the team leader have added a team (which will be saved in the teams table), his user id as well as team id (which is generated from the teams table) will be stored in members table.

My purpose is that once the user create a team, his user id will be auto included in the members table.

The issue I am facing is the team id is being saved as 0. Right now I can only think of doing a get return team id after I have execute the insert teams table query, then execute the insert members table query with the return result. Is there a better way to do it? If so, how should I do it? If not, how should I do it too?

Below is my current code :

Table teams
team_id | game_id | leader_user_id
5       | 1       | 1
6       | 1       | 1
7       | 2       | 1
8       | 2       | 1   

Table members
team_id | user_id
0       | 1         

Controller

$model = new TeamsModel();
                
$newData = [
    'game_id' => $this->request->getVar('game_id'),
    'leader_user_id' => session()->get('user_id')
];

$members = new MembersModel();

$includeLeader = [
    'user_id' => session()->get('user_id'),
    'team_id' => $team_id
];

$model->save($newData);

$members->save($includeLeader);

Thanks in advance guys!


Solution

  • Managed to find out how to solve it by using insertID(). For future reference just in case.

    $model = new TeamsModel();
                    
    $newData = [
        'game_id' => $this->request->getVar('game_id'),
        'leader_user_id' => session()->get('user_id')
    ];
    
    $model->save($newData);
    
    $team_id = $model->insertID();
    
    $members = new MembersModel();
    
    $includeLeader = [
        'user_id' => session()->get('user_id'),
        'team_id' => $team_id
    ];
    
    $members->save($includeLeader);