我的应用程序中有Post和Category实体。他们有一个ManyToMany关系。另外,我使用FosRestBundle处理请求。问题是,当我创建具有给定类别的帖子时,他们不与之关联。而是创建新类别并将其与帖子关联。我想将这些类别ID分配给发布,而不是忽略。 这是我发送到服务器的json。
{
"title":"Post title #1",
"content":"Post content #1",
"excerpt":null,
"alias":"post-title-1",
"image":null,
"status":"draft",
"categories":[
{
"id":301,
"title":"Category title #0",
"content":"Post content #0",
"status":"published",
"alias":"category-title-0",
"image":null,
"created_at":"2018-06-25T16:15:30+00:00",
"updated_at":"2018-06-25T16:15:30+00:00"
},
{
"id":302,
"title":"Category title #1",
"content":"Post content #1",
"status":"published",
"alias":"category-title-1",
"image":null,
"created_at":"2018-06-25T16:15:30+00:00",
"updated_at":"2018-06-25T16:15:30+00:00"
}
]
}
PostController.php
public function update(Post $post, Request $request)
{
// Set post type to default TYPE_POST
$post->setType(Post::TYPE_POST);
$form = $this->createForm(PostType::class, $post);
// Fill the form with submitted data
$form->submit($request->request->all());
// Validate form
if ($form->isValid()) {
// Convert alias if needed
$post->setAliasBasedOnTitle();
// Save to database if valid
$this->getDoctrine()->getManager()->flush();
// Transform post data
$manager = new Manager();
$manager->parseIncludes('categories');
$manager->setSerializer(new DataSerializer());
// Prepare data for response
$resource = new Item($post, new PostTransformer($this->container));
// Status code 201 Created
return $this->json($manager->createData($resource)->toArray(), 200);
}
// Return form errors
return $this->json(array(
'messages' => $this->getFormErrors($form)
), 400);
}
PostType.php
class PostType extends AbstractType
{
protected $transformer;
public function __construct(JsonToCategoryTransformer $transformer)
{
$this->transformer = $transformer;
}
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title')
->add('content')
->add('excerpt')
->add('alias')
->add('image', EntityType::class, array(
'class' => Image::class
))
->add('categories', CollectionType::class, array(
'entry_type' => CategoryType::class,
'allow_add' => true,
'by_reference' => false,
))
->add('status');
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Post::class,
'csrf_protection' => false,
'cascade_validation' => true,
]);
}
}