Search code examples
symfonydoctrinesymfony4

Fixtures to popualte ManyToOne field from csv data


The entity category has a ManyToOne relation with type so each category has one type, and each type can relate to many categories.

I loaded the type form a csv as follows :

$types = fopen(__DIR__.'/types.csv','r');        
while (!feof($types)){

        $line = fgetcsv($types);
        $data = str_getcsv($line[0],';');
        $t[$i] = new Type();
        $t[$i]->setIdType($data[0]);
        $t[$i]->setDescription($data[1]);

        $manager->persist($t[$i]);
        $manager->flush();
        $i++;
    }

    fclose($agregatnational);

Now I have to load the categories the same way : reading from a csv and inserting the values to a relation field without breaking the relation (read the id from the csv then search for the type object that has this id, map that object to the current category).

Keep in mind that I can't generate random id's. Can someone help please ?


Solution

  • I don't know how your classes look like, but it seem like you save the original Id of the type in a field called idType. If that's the case you can use ist to get the persisted entity:

    $categories = fopen(__DIR__.'/categories.csv','r');        
    while (!feof($categories)){
    
        $line = fgetcsv($categories);
        $data = str_getcsv($line[0],';');
    
        $type = $manager->getRepository('Type::class')->findOneBy(['idType' => data[1]);
    
        $new = new Category();
        $new->setType($type);
        $new->setName($data[0);
    
        $manager->persist($new);
        $manager->flush();
        $i++;
    }
    

    I hope this helps.