A
A
Alexey Nikolaev2018-10-11 12:50:54
symfony
Alexey Nikolaev, 2018-10-11 12:50:54

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;
}

In addition, my connection implies uniqueness, i.e. One meta post can have only one task, but a task can have many meta posts.
How to do? ManyToOne, which allows you to return collections, will not work, because it involves many tasks to one meta, and this is not my case.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
Flying, 2018-10-11
@Heian

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 $metais 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
}

or directly in the method:
public function getMeta() : Collection
{
    if (!$this->meta) {
        $this->meta = new ArrayCollection();
    }
    return $this->meta;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question