Git Product home page Git Product logo

yii2-adjacency-list's People

Contributors

paulzi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

yii2-adjacency-list's Issues

Получение предков через with

Можно ли как-то сделать получение предков / потомков через relation?
Например :
$node = Task::find()->where(['id'=>1])->with('parents')->one();

Сортировка нескольких root'ов

Обязательно должен быть 1 общий для всех корневой узел? У меня есть несколько корневых узлов, и я не могу их поменять местами, ошибка Can not move a node before/after root.

Выборка с сортировкой

Долго крутил Ваш behavior, не смог добится выбрать отсортированные строки в логичной последовательности, когда дети идут сразу за родителем.

Все методы getDescendants* возвращают сначала родителей, потом детей (которые между собой отсортированы). Но хотелось бы чтобы дети последовательно шли за родителями (аналог Nested set, когда делается обычная выборка с сортировкой по left).

Для нагруженных операций мне подходит именно adjacency, но редактировать его как-то же надо и поэтому нужно вывести список в логическом порядке. А писать рекурсию с учетом того, что используешь behavior для облегчения кода - как-то нехорошо.

Может чего упустил, но беглый взгляд по коду поведения не помог.

How to get whole tree into one-level array?

Hello! Could you please help me to get the whole tree with correct sorting into one-level array and with some prepends to array values, according to its level? For getting something like this:

$data = [
    1 => 'Root Category',
    2 => '----Category 1',
    3 => '--------Category 1.1',
    4 => '--------Category 1.2',
    5 => '----Category 2',
    6 => '--------Category 2.1',
    7 => '--------Category 2.2',
    8 => '--------Category 2.3',
    // ...
];

The array keys should be the node ID's, and array values - node names with prepend symbol (for example "----" for first node depth level, "--------" for second and so on.). This array can be then used in dropDownList for selecting category.
I created function, but it returns multilevel array, and dropDownList generates unnecessary opt-groups.

public static function treeDropDownWithSpaces($node = null, $space = '')
{
    if (!$node) {
        $node = self::findOne(1)->populateTree();
    }
    $data[$node->id] = $space . $node->name;
    if ($node->children) {
        $space = '----' . $space;
        foreach ($node->children as $child) {
            $data[$child->id] = self::treeDropDownWithSpaces($child, $space);
        }
    }
    return $data;
}

Thanks for help!

Get all siblings

Hello, thank you for this great extension.

Is there a better (more elegant/faster) way to do this?

$node->getParent()->one()->getDescendants()->all()

Cheers,
R

Добавить проверку на рекурсию

Если вдруг parent_id ссылается на себя, выборка родителей впадает в бесконечную рекурсию, было бы неплохо отлавливать и кидать exception или останавливаться на таком элементе.

Table alias error

I get this error

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'categories.parent_id' in 'where clause'
The SQL being executed was: SELECT MAX(sort) FROM `categories` `cat` WHERE categories.`parent_id`=4

Category model:

    public static function find()
    {
        return (new CategoryQuery(get_called_class()))->alias('cat');
    }

The problem is in using $this->owner->tableName()

Improve migration example code README.md

Необходимо добавить в пример миграции поле name, иначе это вводит в заблуждение и выдает ошибку.
Та же самая проблема с другими репами, которые описывают поиск по дереву

parent_id = null

Здравствуйте!

При создании ROOT ноды в параметре parent_id прописывается в MySQL как NULL
В этом случае нет возможности перенести другую ноду по отношению к этой по before/after

А вот если эту ноду (с параметром parent_id = NULL) перенести дочерней к какой-нибудь другой ноде и затем перетянуть обратно, то parent_id у нее уже 0 и все работает корректно...

Можно ли как-то при создании ROOT ноды сделать parent_id = 0?

P.S. Хотя и с нулевым parent_id insertBefore/After не всегда переносят ноду... Непонятно

Версия нестабильная

Здравствуйте! Не устанавливается через composer, пишет, что версия нестабильная. Так и должно быть?:-)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.