主义ManyToMany在相同实体重复输入错误 [英] Doctrine ManyToMany on Same Entity Duplicate Entry Error
问题描述
我必须将相同的字段与不同的参数相关联。
I have to associate the same field with different parameters.
ManyToMany:
ManyToMany:
/**
* @ORM\ManyToMany(targetEntity="BRCN\TaxonomyBundle\Entity\Taxonomy", mappedBy="genderCategories")
*/
private $genders;
/**
* @ORM\ManyToMany(targetEntity="BRCN\TaxonomyBundle\Entity\Taxonomy", inversedBy="genders")
* @ORM\JoinTable(name="menu_relations",
* joinColumns={@ORM\JoinColumn(name="gender_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="category_id", referencedColumnName="id")}
* )
*/
private $genderCategories;
这些变量在相同的表id中使用相同的列名。
These variables are using the same column name in the same table "id".
当我查看menu_relations表时,我看到与我的参数相关联的两个主键。
When i look at the "menu_relations" table, i see two primary key associated with my parameters.
当我尝试插入新的记录,我收到这个错误:
When i try to insert new records, i'm getting this error:
执行'INSERT INTO menu_relations
(gender_id,category_id) VALUES(?,?)'与params [94,1]:
An exception occurred while executing 'INSERT INTO menu_relations (gender_id, category_id) VALUES (?, ?)' with params [94, 1]:
SQLSTATE [23000]:完整性约束违规:1062重复条目
'94 -1 '关键'PRIMARY'
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '94-1' for key 'PRIMARY'
插入值:
if($request->isXmlHttpRequest()) {
$categories = $request->request->get('category');
foreach($categories as $key => $value) {
/** @var $gender \BRCN\TaxonomyBundle\Entity\Taxonomy */
$gender = $em->find('BRCNTaxonomyBundle:Taxonomy', $key);
if($gender) {
foreach($value as $category) {
$category = $em->find('BRCNTaxonomyBundle:Taxonomy', $category);
$gender->addGenderCategory($category);
$em->persist($gender);
}
$em->flush();
}
}
return JsonResponse::create([
'status' => true,
'message' => 'İlişkilendirme Başarılı'
]);
}
推荐答案
你可以利用Doctrine的索引关联,以避免添加重复的关系
You could take advantage of Doctrine's indexed associations to avoid adding duplicate relationships.
以下代码将按 category_id
$ genderCategories >,所以它永远不会包含多个具有相同ID的类别。
The code below will index $genderCategories
by category_id
, so it will never contain more than one category with the same id.
请注意在 indexBy
注释。
/**
* @ORM\ManyToMany(targetEntity="BRCN\TaxonomyBundle\Entity\Taxonomy", inversedBy="genders", indexBy="id")
* @ORM\JoinTable(name="menu_relations",
* joinColumns={@ORM\JoinColumn(name="gender_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="category_id", referencedColumnName="id")}
* )
*/
private $genderCategories;
public addGenderCategory($category) {
$this->genderCategories[$category->getId()] = $category;
}
Sidenote
我建议将持久化
调用到您的循环中以提高性能。
I suggest pulling the persist
call out of your loop to improve performance.
foreach($value as $category) {
$category = $em->find('BRCNTaxonomyBundle:Taxonomy', $category);
$gender->addGenderCategory($category);
}
$em->persist($gender);
这篇关于主义ManyToMany在相同实体重复输入错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!