У меня есть две сущности для продуктов и переводов:
class ProductEntity
{
/**
* @Id
* @var string
* @Column(type="string", length=3)
*/
protected $code;
/**
* @OneToMany(targetEntity="ProductTranslationEntity", mappedBy="product")
*/
private $translations;
public function __construct()
{
$this->translations = new ArrayCollection();
}
/.../ getters and setters
public function addTranslation(ProductTranslationEntity $productTranslation)
{
$this->translations->add($productTranslation);
}
public function clearTranslations()
{
$this->translations->clear();
}
}
.
class ProductTranslationEntity
{
/**
* @ManyToOne(targetEntity="ProductEntity", inversedBy="translations")
* @JoinColumn(name="product_code", referencedColumnName="code", onDelete="CASCADE")
* @Id
*/
private $product;
/**
* @var string
* @Column(type="string", name="language_code", length=5)
* @Id
*/
protected $languageCode;
/**
* @var string
* @Column(type="string", name="product_name", length=128)
*/
protected $productName;
/.../ getters and setters
}
Мне нравится заменять все переводы новыми, из массива, подобного этому:
['en' => ['name' => 'name_en'], 'de' => ['name' => 'name_de']];
Поскольку в этом массиве у меня есть набор всех поддерживаемых языков, лучший способ, который я вижу, - удалить все существующие переводы и поставить новые:
$product // Existing product entity
$product->clearTranslations();
$this->entityManager->flush($product);
foreach ($translations as $code => $translation) {
$t = new ProductTranslationEntity();
$t->setProduct($product);
$t->setLanguageCode($code);
$t->setProductName($translation['name']);
$this->entityManager->persist($t);
$product->addTranslation($t);
}
$this->entityManager->flush($product);
Эторешение не работает, потому что после первого $this->entityManager->flush($product);
в базе данных все еще есть переводы, поэтому я получаю сообщение об ошибке дубликатов.
Что я сделал неправильно в своем решении?Или, может быть, есть другой способ решить эту проблему?