public function attach_files($document) {
        global $DB;

        $postid = $document->get('itemid');

        try {
            $post = $this->get_post($postid);
        } catch (\dml_missing_record_exception $e) {
            unset($this->postsdata[$postid]);
            debugging('Could not get record to attach files to '.$document->get('id'), DEBUG_DEVELOPER);
            return;
        }

        // Because this is used during indexing, we don't want to cache posts. Would result in memory leak.
        unset($this->postsdata[$postid]);

        $cm = $this->get_cm($this->get_module_name(), $post->forum, $document->get('courseid'));
        $context = \context_module::instance($cm->id);
        $contextid = $context->id;

        $fileareas = $this->get_search_fileareas();
        $component = $this->get_component_name();

        // Get the files and attach them.
        foreach ($fileareas as $filearea) {
            $fs = get_file_storage();
            $files = $fs->get_area_files($contextid, $component, $filearea, $postid, '', false);

            foreach ($files as $file) {
                $document->add_stored_file($file);
            }
        }
    }