I
I
Igor2019-08-25 01:41:35
Doctrine ORM
Igor, 2019-08-25 01:41:35

How to manage categories?

Hello colleagues!
I know that there is a nested set
. It's kind of complicated, I haven't fully understood how it works yet.
Time is running out, and categories need to be managed yesterday.

/** @var Category $parent */
        $parent = $repo->getById(1222); // 1222 идентификатор родителя 

        $p = $parent->getParent(); //  object или null
        $lvl = 0; // Уровень
        while (true) {
            $lvl++; // Повышаю уровень

            if (is_null($p)) { 
                break; // если родителей больше нет
            }
            $p = $p->getParent(); // Получаем родителя
        }
        
        $new_category  = new Category();
        $new_category->setName("children 1");
        $new_category->setParent($parent);
        $new_category->setLvl($lvl);
        
        $this->em->persist($new_category);
        $this->em->flush();

For the level navigation logic, I need to know which level I'm on.
Root categories 0 = lvl and further to increase.
Above, I gave an example of how I was going to calculate the level when creating a new branch.
There is a feeling that this is a clumsy decision and I am digging in the wrong direction.
Maybe there is a working module for working with trees.
Been here
But damn it, "gedmo/doctrine-extensions": "dev-master" doesn't have the required classes to implement.
At the moment, it works like this:
5d61c0b77ab58353727266.gif
In DevTools
5d61c0bfbf771764319412.gif
The tree_history array just stores the levels, the level is the key of the node identifier.
To complete the picture, I request the levels using the API
{{ADMIN_BASE_URL}}/category.get?count=1000&offset=0&sort=DESC&parent_id=52
{
    "count": 47,
    "items": [
        {
            "alt_name": "Розовые авто",
            "name": "Авто",
            "id": 2,
            "lvl": "0"
        },
        {
            "alt_name": null,
            "name": "Безопасность",
            "id": 3,
            "lvl": "0"
        },
        {
            "alt_name": null,
            "name": "Бизнес",
            "id": 4,
            "lvl": "0"
        },
...

If we don't pass parent_id then we'll get all the root nodes. The
question is, is there a more elegant solution?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question