Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear or empty the Array Collection in doctrine symfony

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()

like image 840
user17 Avatar asked Aug 10 '12 04:08

user17


1 Answers

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!)

like image 171
Thomas Kelley Avatar answered Nov 07 '22 03:11

Thomas Kelley