B
B
Bovv2018-07-23 23:14:34
symfony
Bovv, 2018-07-23 23:14:34

How to pick up only one entity from the collection when serializing an object using JMSSerializerBundle?

Used by : Symfony 4.1, FOSRestBundle, JMSSerializerBundle
There is an entity Articlethat has a one-to-many two-way relationship with ArticleImage.

class Article
{

  private $id;

  ...

  /**
   * @ORM\OneToMany(targetEntity="ArticleImage", mappedBy="article")
   */
  private $images;

  ...
}

class ArticleImage
{

  private $id;

  private $file;

  ...

  /**
   * @ORM\ManyToOne(targetEntity="Article", inversedBy="images")
   */
  private $article;

  private $isPreview;

  ...
}

There are two serialization contexts: list and detail . How can I set it up so that in the list context , only one entity ArticleImagethat $isPreviewhas a value of true, and not the entire collection, gets into the result?
There is an idea to hang up an EventListener and, depending on the context, manually remove all unnecessary ArticleImageitems from the collection before serialization, but somehow this option seems to me not the most optimal.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jaxel, 2018-07-24
@jaxel

The easiest way is to make a method like getPreview. In it, give the desired element and serialize it as a VirtualProperty

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question