public function getRootId()
    {
        if (self::$rootId !== null) {
            return self::$rootId;
        }

        // Get the root item.
        $k = $this->getKeyName();

        // Test for a unique record with parent_id = 0
        $query = $this->db->getQuery(true)
            ->select($k)
            ->from($this->db->quoteName($this->table))
            ->where('parent_id = 0');

        $result = $this->db->setQuery($query)->loadColumn();

        if (count($result) == 1) {
            return self::$rootId = $result[0];
        }

        // Test for a unique record with lft = 0
        $query->clear()
            ->select($k)
            ->from($this->db->quoteName($this->table))
            ->where('lft = 0');

        $result = $this->db->setQuery($query)->loadColumn();

        if (count($result) == 1) {
            return self::$rootId = $result[0];
        }

        throw new NestedHandleException(sprintf('%s::getRootId', get_class($this)));
    }