/** * Get tree of terms * @param $vid * @param bool $parentID * @return array */ public static function getTree($vid, $parentID = false) { $rows = static::findHierarchy($vid, $parentID); $hierarchy = static::indexByChild($rows); /** @var TaxonomyTerm [] $models */ $models = TaxonomyTerm::find()->indexBy('id')->where(['vid' => $vid])->all(); //add child to parents by list foreach ($hierarchy as $cID => $pID) { if (isset($models[$pID]) && isset($models[$cID])) { $models[$pID]->addChild($models[$cID]); } } $roots = []; foreach ($models as $id => $model) { if (isset($hierarchy[$id]) && $hierarchy[$id] == 0) { $roots[$id] = $model; } } return isset($models[$parentID]) ? $models[$parentID]->child : $roots; }
/** * Find model by ID. * * @param integer|array $id Model ID * * @return TaxonomyTerm * * @throws HttpException 404 error if model not found */ protected function findModel($id, $vid) { if (is_array($id)) { $model = TaxonomyTerm::find()->where(['vid' => $vid, 'id' => $id])->all(); } else { $model = TaxonomyTerm::find()->where(['vid' => $vid, 'id' => $id])->one(); } if ($model !== null) { return $model; } else { throw new HttpException(404); } }