Symfony4.2下DataFixtures导入CSV至关联实体报错求助
Let's break down your issue and fix it step by step:
1. The Root Cause: Wrong Dependency Class
The error you're seeing happens because your LocationCountryFixtures::getDependencies() method is returning an entity class (Translate::class) instead of the fixture class (TranslateFixtures::class). Doctrine Fixtures relies on dependencies between fixture classes, not the entities they manage.
2. Fixed LocationCountryFixtures Code
Update your getDependencies() method to reference the correct fixture class, and make sure you import it at the top:
// src/DataFixtures/LocationCountryFixtures.php use App\DataFixtures\TranslateFixtures; // Add this import // ... rest of your existing use statements class LocationCountryFixtures extends Fixture implements DependentFixtureInterface { // ... your existing code for loading fixtures public function getDependencies() { return [ TranslateFixtures::class, // Replace Translate::class with this ]; } }
3. Answering Your addReference Timing Question
Your current placement of $this->addReference('country'.$item[0], $obj); (after $manager->persist($obj) but before $manager->flush()) is perfectly valid.
References work as long as the object is managed by the EntityManager (which happens when you call persist()). You could even call addReference() after flush() and it would still work, but your current approach is clean and follows best practices.
4. Bonus: Reduce Code Duplication
Since both fixtures are reading the same CSV file, you can avoid duplicate code by extracting the CSV reading logic into a reusable helper method. For example, add this to a base fixture class or a trait:
// Example helper method in a base fixture protected function loadCountriesCsv(): array { $csv_path = __DIR__.'/../path/to/your/countries.csv'; // Update this path to your actual CSV location $csv_max_line_length = 1000; $csv_delimiter = ','; $csv_enclosure = '"'; $countries = []; if ($csv_handle = fopen($csv_path, 'r')) { while ($item = fgetcsv($csv_handle, $csv_max_line_length, $csv_delimiter, $csv_enclosure)) { $countries[] = $item; } fclose($csv_handle); } return $countries; }
Then use this method in both fixtures to load the CSV data once, making your code cleaner and easier to maintain.
内容的提问来源于stack exchange,提问作者bcag2

