public function beforeSave($insert) { if (parent::beforeSave($insert)) { if ($this->parent === null || $this->parent->isNewRecord) { $this->level = 0; } else { $this->level = $this->parent->level + 1; } if ($this->isNewRecord) { $query = new Query(); $query->select(['position']); $query->from(self::tableName()); $query->orderBy('position DESC'); if ($this->parent_id) { $query->where('parent_id=:parent_id'); $query->params([':parent_id' => $this->parent_id]); } else { $query->where('parent_id is NULL'); } $last = $query->one(); $this->position = $last ? $last['position'] + 1 : 0; } return true; } else { return false; } }