I have the Array collection of objects like this
Class User
{
private $tasks;
}
How can i empty or clear the collection once user gets loaded from database.
When i query for user then Doctrine will lazy load the tasks in user object but i want to first clear those tasks
something like
$user->getTasks().empty()
First of all, I imagine your User entity's constructor looks something like this:
class User
{
public function __construct()
{
...
$this->tasks = new \Doctrine\Common\Collections\ArrayCollection();
...
}
}
If that's not correct so far, then stop reading, and correct me in the comments :)
Note that the ArrayCollection class was created by Doctrine. Symfony and most of its components are pretty good about documenting the classes. When you look up that class, you'll find:
https://www.doctrine-project.org/api/collections/latest/Doctrine/Common/Collections/ArrayCollection.html
(of course, make sure you're on the same version; otherwise, try to find the documentation for your version)
The documentation lists all the methods available to the ArrayCollection object. Among them: clear()
.
That said, adding a new method to the User class should work:
class User
{
public function clearTasks()
{
$this->getTasks()->clear();
}
}
Then, on the User object, just call:
$user->clearTasks();
(and don't forget to persist to the database!)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With