Okay, I believe I see what you're trying to achieve.
You are doing some sort of import, and during the foreach
loop, you're creating Team
entities that get associated with your DataPlayer
. Obviously you don't want to end up making multiple Teams after the first one has been made with a certain tag, but since you haven't performed a flush()
using the Entity Manager yet, you can't findOneByTag()
because the Team doesn't yet exist in the database.
This is obviously problematic. So what's the solution? Create a temporary array!
$tempTeams = array();
foreach($teams as $team){
$info = explode(',', str_replace("'", "", $team));
if (isset($tempTeams[$info[1]])) {
$db_team = $tempTeams[$info[1]];
} else {
$db_team = $db->getRepository("ApplicationTestBundle:Team")->findOneByTag($info[1]);
}
if(!$db_team){
$db_team = new Team();
$db_team->setTag($info[1]);
$db_team->setName($info[0]);
$em->persist($db_team);
$tempTeams[$info[1]] = $db_team;
}
$dataT = new DataTeam();
$dataT->setTeam($db_team);
$em->persist($dataT);
$db_team = false; // Need to make sure $db_team is cleared out for the next iteration of the foreach
}
This takes all of your temporary PHP objects before persistence and buffers it into the temporary array, which allows you to recall your new Objects by tag name with no problems. The other solution is to $em->flush();
after $em->persist($db_team);
You can then access the $tempTeams
array for later lookups (I believe there was an issue with using $info[4]
for the tag this time):
foreach($players as $player){
$info = explode(',', str_replace("'", "", $player));
$db_player = $db->getRepository("ApplicationTestBundle:Player")->findOneByPseudo($info[1]);
$dataJ = new DataPlayer();
$dataJ->setJoueur($db_player);
if (isset($tempTeams[$info[4]])) {
$db_team = $tempTeams[$info[4]];
} else {
$db_team = $db->getRepository("ApplicationTestBundle:Team")->findOneByTag($info[4]);
}
$dataJ->setTeam($db_team);
$em->persist($dataJ);
$db_team = false;
}