1

For example, let's say that I have two entities, Article and Comment, comments mapped to articles through an unidirectional manyToOne relation. What I want to know is, if it's possible to serialize relation, but in the mappedOne, only serialize the ID.

For example, if I serialize an article, I'll get a complete json representation of it (including id, title, content...).

{"title":"article title", "content":"article content", "id":"7"}

But if I serialize a comment, I want it to hava a complete json representation of itself, but in the article field, I only want the article id.

{"id":"2", "author":"foo","content":"comment content","linked_article":{"id":"7"}}

Thanks a lot !

ovesco
  • 633
  • 1
  • 8
  • 22
  • duplicate maybe ? http://stackoverflow.com/questions/15993565/serializing-entity-relation-only-to-id-with-jms-serializer – zizoujab Mar 24 '15 at 20:33

1 Answers1

1

In the controller action (getCommentAction) do you have serializer groups in the annotation?

I think that by putting this annotation over the controller action

@Rest\View(serializerGroups={"id","comment"}

And in your Article entity putting

/**
 * @JMS\Serializer\Annotation\Groups({"id", "article"})
*/
protected $id;

It should work.

mickadoo
  • 3,337
  • 1
  • 25
  • 38
  • and what if for some cases I want the only id, but for other cases, I want full article? I think it's better to use @Accessor annotation then. – Oleg Abrazhaev May 26 '17 at 11:02
  • 1
    My understanding of @Access is that it just tells the serializer which method to use to get / set a property. If you only want to dynamically set what should be serialized you could always pass the group in with the request like `GET /users?return=id` or `GET /users?return=id,comment`, which would decide which serializer groups to use – mickadoo May 26 '17 at 17:13
  • In my case, I need to hardcore serialization rule for different relations. For example, we have Comments-Article and Promote-Article. If I will set rule on an Article site it will be serialized as id for Comments and Promote. But I need id for Comments and full for Promote. And not only for rest view. So, the rule for Artcile should be configured on each relation owner side. – Oleg Abrazhaev May 28 '17 at 04:40