嵌入 SQL 查询自定义字段

嵌入SQL查询自定义字段

方法1

效果

image-20240831205520-mpw6ehr

//!js
return (async () => {
    const sql = `
        select * from blocks where type = 'd' limit 2;
    `;
    const result = await query(sql);
    render(result);

    function render(result) {
        let html = '';
        result.forEach(item => {
            html += `<div class="protyle-wysiwyg__embed" data-id="${item.root_id}"><div data-node-index="1" data-type="NodeParagraph" class="p" updated=""><div contenteditable="true" spellcheck="false"><span data-type="block-ref" data-id="${item.id}" data-subtype="d" style="">${item.content}</span><span style="margin-left:20px;color:#666;">${item.hpath}</span><span style="float:right;color:#666;">${formatDateTime(item.created)}</span></div><div class="protyle-attr" contenteditable="false"></div></div></div>`;
        });

        setTimeout(() => {
            item.querySelector('.b3-form__space--small').outerHTML = html;
        }, 40);
    }

    function formatDateTime(str) {
        const year = str.substring(0, 4);
        const month = str.substring(4, 6);
        const day = str.substring(6, 8);
        const hours = str.substring(8, 10);
        const minutes = str.substring(10, 12);
        const seconds = str.substring(12);
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }

    // 通过SQL查询数据
    async function query(sql) {
        const result = await fetchSyncPost('/api/query/sql', { "stmt": sql });
        if (result.code !== 0) {
            console.error("查询数据库出错", result.msg);
            return [];
        }
        return result.data;
    }

    // 请求api
    async function fetchSyncPost(url, data) {
        const init = {
            method: "POST",
        };
        if (data) {
            if (data instanceof FormData) {
                init.body = data;
            } else {
                init.body = JSON.stringify(data);
            }
        }
        try {
            const res = await fetch(url, init);
            const res2 = await res.json();
            return res2;
        } catch (e) {
            console.log(e)
            return [];
        }
    }

// 固定返回空值
return [];
})();

方法2

参考 查询不在数据库中的文档

image.png

留下你的脚步
推荐阅读