So, I have an array of users, and each user has an ID and a list of games. I store it in my database as pairs of userID and gameID.
Every time I'm going to change the games for each user, I need to wipe the old ones and then insert the new ones, so I did this:
foreach($users as $user) {
$where['id_user'] = $user->id;
$this->tableUsersGames->delete($where);
foreach($user->games as $game){
$data['id_user'] = $user->id;
$data['id_game'] = $game->id;
$this->tableUsersGames->insert($data);
}
}
But it only inserts the last user/games in the list. What I did to solve this was to instead have two foreach
loops, one for deleting the data, and then another one to insert it, so it's now working fine.
What I wanted to know is why didn't this work? I even put some echoes in there to make sure it was running the right order, and it was.
OK, editing for clarification.
The $users variable looks like this:
[
{id: 1, games: [
{id: 3, name: 'xyz'},
{id: 5, name: 'xyz'}
]
},
{id: 2, games: [
{id: 2, name: 'xyz'},
{id: 9, name: 'xyz'}
]
}
]
And the framework does exactly what you'd expect it to do, no commit needed.