Hi everyone, I've got a static text object and its historical revisions: StaticText 1 <→ N StaticTextHistory. So I made these relations:
StaticText.php
/**
* @ORM\OneToMany(targetEntity="\Text\Entity\StaticTextHistory", mappedBy="staticText")
* @var ArrayCollection
*/
protected $history;
public function __construct()
{
$this->history = new ArrayCollection();
}
StaticTextHistory.php
/**
* @ORM\ManyToOne(targetEntity="\Text\Entity\StaticText", inversedBy="history")
* @ORM\JoinColumn(name="static_text_id", referencedColumnName="id", onDelete="CASCADE")
* @var \Text\Entity\StaticText
*/
protected $staticText;
I am trying to save StaticTextHistory object as follows:
$staticText->history->add($staticTextHistory);
And I always get error:
Call to a member function add() on a non-object
When I dump $this->staticText->history
, property history
is an array, not an ArrayCollection.
Thanks a lot in advance.
EDIT: I have fixed this issue using getter for history property:
$staticText->getHistory()->add($staticTextHistory);
But I'm still interested what's wrong. Does it have to do anything with BaseEntity's code (starting from 240):
if ($this->$name instanceof Collection) {
$coll = $this->$name->toArray();
return $coll;
}
//...
This question was answered by Filip Procházka, you can jump directly to the answer
Yes, it does. It's intentional. You should not let the collection “escape” the object, because you would be opening internal state of the object to the outside.
Better would be to use either magic method, that is provided
by BaseEntity
$staticText->addHistory($staticTextHistory);
or write your own method.
Thanks for the magic