Страница 1 из 1

Nested Set with Yii2

Добавлено: 2019.09.06, 19:21
nulled
Приветствую! Скопировал все с https://www.yiiframework.com/wiki/2549/ ... revision=1, при записи в бд получаю:

Код: Выделить всё

SQLSTATE[HY000]: General error: 1364 Field 'tree' doesn't have a default value
The SQL being executed was: INSERT INTO `category` (`name`, `position`, `created_at`, `updated_at`, `lft`, `rgt`, `depth`) VALUES ('Категория 1', 1, 1567786272, 1567786272, 1, 2, 0)
Error Info: Array
(
    [0] => HY000
    [1] => 1364
    [2] => Field 'tree' doesn't have a default value
)
Код выкладывать смысла не вижу, копия с примера. Версия Yii 2.0.26

Re: Nested Set with Yii2

Добавлено: 2019.09.06, 22:56
yiiliveext
Скорее всего у вас 'treeAttribute' => false, не вставляется поле tree

Re: Nested Set with Yii2

Добавлено: 2019.09.07, 07:11
proctoleha
В таких случаях всегда смотрим оригинал: https://github.com/creocoder/yii2-nested-sets

А там, внезапно:
Run the following command

$ yii migrate/create create_menu_table
Open the /path/to/migrations/m_xxxxxx_xxxxxx_create_menu_table.php file, inside the up() method add the following

$this->createTable('{{%menu}}', [
'id' => $this->primaryKey(),
//'tree' => $this->integer()->notNull(),
'lft' => $this->integer()->notNull(),
'rgt' => $this->integer()->notNull(),
'depth' => $this->integer()->notNull(),
'name' => $this->string()->notNull(),
]);
To use multiple tree mode uncomment tree field.
Поле tree используется только тогда, когда в одной таблице у вас несколько деревьев.

Т.е. ман ф топку

Re: Nested Set with Yii2

Добавлено: 2019.09.07, 08:59
nulled
yiiliveext писал(а): 2019.09.06, 22:56 Скорее всего у вас 'treeAttribute' => false, не вставляется поле tree
Спасибо за ответ, вот что в поведении:

Код: Выделить всё

public function behaviors() {
        return [
            \yii\behaviors\TimeStampBehavior::class,
            'tree' => [
                'class' => NestedSetsBehavior::class,
                'treeAttribute' => 'tree',
                // 'leftAttribute' => 'lft',
                // 'rightAttribute' => 'rgt',
                // 'depthAttribute' => 'depth',
            ],
        ];
    }

Re: Nested Set with Yii2

Добавлено: 2019.09.07, 09:01
nulled
proctoleha писал(а): 2019.09.07, 07:11 В таких случаях всегда смотрим оригинал: https://github.com/creocoder/yii2-nested-sets

А там, внезапно:
Run the following command

$ yii migrate/create create_menu_table
Open the /path/to/migrations/m_xxxxxx_xxxxxx_create_menu_table.php file, inside the up() method add the following

$this->createTable('{{%menu}}', [
'id' => $this->primaryKey(),
//'tree' => $this->integer()->notNull(),
'lft' => $this->integer()->notNull(),
'rgt' => $this->integer()->notNull(),
'depth' => $this->integer()->notNull(),
'name' => $this->string()->notNull(),
]);
To use multiple tree mode uncomment tree field.
Поле tree используется только тогда, когда в одной таблице у вас несколько деревьев.

Т.е. ман ф топку
Так вот и хотелось бы использовать множество деревьев

Re: Nested Set with Yii2

Добавлено: 2019.09.07, 09:50
nulled
В общем разрешил в бд для поля tree (null), заработало, НО так и не понял почему так.
Может знающие подскажут?
Это ж костыль 100% или не?

Re: Nested Set with Yii2

Добавлено: 2019.09.07, 10:06
nulled
А может и нет
В поведении перед записью в бд устанавливаются атрибуты:

Код: Выделить всё

protected function beforeInsertRootNode()
    {
        if ($this->treeAttribute === false && $this->owner->find()->roots()->exists()) {
            throw new Exception('Can not create more than one root when "treeAttribute" is false.');
        }

        $this->owner->setAttribute($this->leftAttribute, 1);
        $this->owner->setAttribute($this->rightAttribute, 2);
        $this->owner->setAttribute($this->depthAttribute, 0);
    }
    
Но для поля tree ничего не назначается, а потом обновляем tree:

Код: Выделить всё

    public function afterInsert()
    {
        if ($this->operation === self::OPERATION_MAKE_ROOT && $this->treeAttribute !== false) {
            $this->owner->setAttribute($this->treeAttribute, $this->owner->getPrimaryKey());
            $primaryKey = $this->owner->primaryKey();

            if (!isset($primaryKey[0])) {
                throw new Exception('"' . get_class($this->owner) . '" must have a primary key.');
            }

            $this->owner->updateAll(
                [$this->treeAttribute => $this->owner->getAttribute($this->treeAttribute)],
                [$primaryKey[0] => $this->owner->getAttribute($this->treeAttribute)]
            );
        }

        $this->operation = null;
        $this->node = null;
    }

В документации ошибка? Правильно понял?

Re: Nested Set with Yii2

Добавлено: 2019.09.07, 11:39
yiiliveext
nulled писал(а): 2019.09.07, 10:06 В документации ошибка? Правильно понял?
Да

Re: Nested Set with Yii2

Добавлено: 2019.11.06, 09:01
b.alex
Я так и не понял в чем проблема и каrое решение поставить на tree NULL?

Re: Nested Set with Yii2

Добавлено: 2019.11.06, 15:12
nulled
b.alex писал(а): 2019.11.06, 09:01 Я так и не понял в чем проблема и каrое решение поставить на tree NULL?
Разрешите для поля tree (null), сначала идет запись, а потом обновление tree. Т.к. базой запрещено пустое значение, вылетает ошибка.

Re: Nested Set with Yii2

Добавлено: 2019.11.07, 07:15
b.alex
nulled писал(а): 2019.11.06, 15:12
b.alex писал(а): 2019.11.06, 09:01 Я так и не понял в чем проблема и каrое решение поставить на tree NULL?
Разрешите для поля tree (null), сначала идет запись, а потом обновление tree. Т.к. базой запрещено пустое значение, вылетает ошибка.
Спасибо уже понял, там в документации у него ошибка в миграции что на поле tree стоит notNull