在Symfony4.2下,我有一个 Translate 实体(id,gb_name,fr_name)和 LocationCountry 实体(id,ISO3166-2名称:GB,FR,DE …,translate_id)
我定义了一个包含255个国家(“ GB”,“英国”,“ Angleterre” ...)的CSV文件,并希望使用DataFixture将其推送到Translate和LocationCountry实体表中。
我仔细阅读了https://symfony.com/doc/current/bundles/DoctrineFixturesBundle/index.html#sharing-objects-between-fixtures
和
php create fixtures with automatic relations
src / DataFixtures / TranslateFixtures.php:
if ($csv_handle) {
while ($item = fgetcsv($csv_handle, $csv_max_line_length, $csv_delimiter, $csv_enclosure)) {
$obj = new Translate();
$obj->setGbValue($item[1]);
$obj->setFrValue($item[2]);
$this->addReference('country'.$item[0], $obj);
$manager->persist($obj);
}
fclose($csv_handle);
}
$manager->flush();
我不确定 addReference 应该在 flush()之前吗?
src / DataFixtures / LocationCountryFixtures.php:
if ($csv_handle) {
while ($item = fgetcsv($csv_handle, $csv_max_line_length, $csv_delimiter, $csv_enclosure)) {
$translate_country = $this->getReference('country'.$item[0]);
$obj = new LocationCountry();
$obj->setIso3166Name($item[0]);
$obj->setTranslate($translate_country);
$manager->persist($obj);
}
fclose($csv_handle);
}
$manager->flush();
}
public function getDependencies() {
return array(
Translate::class,
);
}
如果我删除了 addReference ,则翻译实体已填充完毕。
但是使用上面的代码,它将返回错误:
In SymfonyFixturesLoader.php line 76:
The "App\Entity\Translate" fixture class is trying to be loaded, but is not available. Make sure this class is defined as a service and tagged with "doctrine.fixture.orm".
我认为使用正确:
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\DataFixtures\DependentFixtureInterface;
use App\Entity\LocationCountry;
use App\Entity\Translate;
感谢您的帮助
答案 0 :(得分:1)
Doctrine按字母顺序加载夹具文件;这就是为什么您会得到一个错误。您可以考虑在灯具中使用功能getOrder
,以设置首先加载哪个功能。
编辑:
由于未在getDependencies
方法中提供正确的类而导致错误:
public function getDependencies() {
return array(
TranslateFixtures::class,
);
}
答案 1 :(得分:0)
在这种情况下,我只是删除src / DataFixtures / TranslateFixtures.php
并更改src / DataFixtures / LocationCountryFixtures.php以完成所有工作:
if ($csv_handle) {
while ($item = fgetcsv($csv_handle, $csv_max_line_length, $csv_delimiter, $csv_enclosure)) {
//$translate_country = $this->getReference('country'.$item[0]);
$country = new LocationCountry();
$translate_country = new Translate();
$translate_country->setGbValue($item[1]);
$translate_country->setFrValue($item[2]);
$country->setIso3166Name($item[0]);
$country->setTranslateCountry($translate_country);
$manager->persist($translate_country);
$manager->persist($country);
}
fclose($csv_handle);
}
$manager->flush();