我有类别分类。我的分类可以有一个或几个类别:
/**
* @ORM\OneToMany(targetEntity="Category", mappedBy="classified", cascade={"persist"}, orphanRemoval=true)
*/
protected $categories;
重要的是要知道我的类别实体具有复合主键:类别的ID和分类。
我想通过选择字段将类别填充到我的分类中:
$builder->add(
$builder->create('categories', ChoiceType::class, [
'choices' => [
'Category 1' => 1,
'Category 2' => 2,
'Category 3' => 3,
'Category 4' => 4,
],
'multiple' => true,
])->addModelTransformer(new CallbackTransformer(
// Transform collection of entities into an array of IDs
function($categories) {
if (!$categories) {
return [];
}
return $categories->map(function(Category $category) {
return $category->getId();
})->toArray();
},
// Reverse transform IDs array from request to a collection of entities
function($categories) {
$items = [];
if ($categories && is_array($categories)) {
foreach ($categories as $id) {
$items[] = new Category($id);
}
}
return $items;
}
))
);
如您所见,我有一个变换器将类别集合转换为ID列表,反之亦然。
在创建我的分类广告时,一切都很好,但版本有问题。
我的问题是,当我提交表单时,我有重复的条目问题:
An exception occurred while executing 'INSERT INTO tv_classified_category (id, classified_id) VALUES (?, ?)' with params [4, 1]:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '4-1' for key 'PRIMARY'
以下是我在handleRequest
之前和之后转储类别列表时发现的内容:
dump($classified->getCategories()->toArray());
$form->handleRequest($request);
if ($form->isValid()) {
dump($classified->getCategories()->toArray());
调试结果:
array:2 [▼
0 => Category {#1036 ▶}
1 => Category {#1038 ▶}
]
array:3 [▼
2 => Category {#4108 ▶}
3 => Category {#4110 ▶}
]
正如您所看到的,在handleRequest调用之前和之后,键之间存在奇怪的不匹配,并且PHP i ds对象是
此致