Reputation: 321
I am trying to write toArray() method in object class. This is class
Collection
class Collection{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
* @Assert\NotBlank()
*/
private $name;
/**
* @ORM\OneToMany(targetEntity="MyMini\CollectionBundle\Entity\CollectionObject", mappedBy="collection", cascade={"all"})
* @ORM\OrderBy({"date_added" = "desc"})
*/
private $collection_objects;
/*getter and setter*/
public function toArray()
{
return [
'id' => $this->getId(),
'name' => $this->name,
'collection_objects' => [
]
];
}
}
How do I get array of collection_objects properties, if type of collection_objects is \Doctrine\Common\Collections\Collection
Upvotes: 3
Views: 3700
Reputation: 83662
\Doctrine\Common\Collections\Collection
is an interface that also provides a toArray()
method. You'll be able to use that method directly on your collection:
public function toArray()
{
return [
'id' => $this->getId(),
'name' => $this->name,
'collection_objects' => $this->collection_objects->toArray()
];
}
There is one problem though. The array returned by \Doctrine\Common\Collections\Collection::toArray()
is an array of \MyMini\CollectionBundle\Entity\CollectionObject
objects and not an array of plain arrays. If your \MyMini\CollectionBundle\Entity\CollectionObject
also facilitates a toArray()
method you can use that to convert these to arrays as well like that for example:
public function toArray()
{
return [
'id' => $this->getId(),
'name' => $this->name,
'collection_objects' => $this->collection_objects->map(
function(\MyMini\CollectionBundle\Entity\CollectionObject $o) {
return $o->toArray();
}
)->toArray()
];
}
Upvotes: 3