Answer the question
In order to leave comments, you need to log in
How to do one-to-many with a collection in Doctrine?
Good day.
There is a table of tasks that can have an unlimited number of meta-records. It would seem a typical one-to-many (one task to many meta-records), but when I directly indicate this, Symphony swears at the collection (says, The return type of method "getMeta" is invalid). But I need to return exactly the collection - a lot of meta-records!
/**
* @ORM\OneToMany(targetEntity="App\Entity\TaskMeta", mappedBy="task")
*/
private $meta;
public function getMeta() : ? \Collection
{
return $this->meta;
}
Answer the question
In order to leave comments, you need to log in
You have potentially two errors in the above code:
1. You specify as the return type \Collection
, while Doctrine collections are \Doctrine\Common\Collections\Collection
2. Your code does not create this collection, respectively, if it is not an entity created by Doctrine itself when loading data from the database - the value $meta
is null
. The correct approach is to either initialize the collections in the constructor:
public function __construct() {
$this->meta = new ArrayCollection(); // где ArrayCollection это \Doctrine\Common\Collections\ArrayCollection
}
public function getMeta() : Collection
{
if (!$this->meta) {
$this->meta = new ArrayCollection();
}
return $this->meta;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question