Home > Software design >  How can I create a method that returns an array of IDs?
How can I create a method that returns an array of IDs?

Time:06-20

I try to create a method that returns an array of IDs:

   /**
    * @ORM\OneToMany(targetEntity="App\Entity\Event", mappedBy="project")
    *
    * @Serializer\Expose()
    */
    private $event;



    public function __construct()
    {
        $this->enabled = false;
        $this->event = new ArrayCollection();
    }


     /**
     * @return array<string, mixed>
     *
     * @Serializer\VirtualProperty()
     * @Serializer\SerializedName("event")
     */
    public function getEvent(): ?array
    {
        if ($event = $this->getEvent()) {
            return [
                'id' => $event->getId(),
            ];
        }

        return null;
    }

But I get an error message in my console:

The "selection" field with the path "event/" expects an array of ids as value but received an array of objects instead. Is it possible that your API returns an array serialized objects?

To fix this I tried:

  public function getEvent()
    {
        return $this->event;
    }


        /**
     * @return array<string, mixed>
     *
     * @Serializer\VirtualProperty()
     * @Serializer\SerializedName("event")
     */
    public function getEventData(): ?array
    {
        if ($event = $this->getEvent()) {
            return [
                'id' => $event->getId(),
            ];
        }

        return null;
    }

But here I get the error message:

Attempted to call an undefined method named "getId" of class "Doctrine\ORM\PersistentCollection".

CodePudding user response:

$event is a OneToMany relationship, which mean it would be better if you renamed it $events.

$event is an ArrayCollection made of Event object.

Which mean that if you want to get an array made only of ids, you need to turn your ArrayCollection into an array of ID.

So you could use ArrayCollection map method to apply a callback on each element to return an array of id.

Example:

public function getEventData(): ?array
    {
        return $this->event->map(fn($e) => $e->getId())->toArray();
    }

map (from doctrine doc)

Applies the given function to each element in the collection and returns a new collection with the elements returned by the function.

We use toArray to turn the ArrayCollection into an array.

  • Related