如何从Sequelize-Sqlite数据库请求排行榜格式的数据?

mftmpeh8  于 2022-11-14  发布在  SQLite
关注(0)|答案(2)|浏览(143)

我试图通过序列化从Sqlite数据库中拉用户和渔获,并在消息回复中显示一个按渔获量排名的排行榜。
我的Sqlite数据库如下所示

const Tags = sequelize.define('tags', {
user: {
    type: Sequelize.STRING,
    unique: true,
},
catches: {
    type: Sequelize.INTEGER,
    defaultValue: 0,
    allowNull: false,
},

我尝试将数据库中的前10个值压入数组,并使用discord.js指南建议的排行榜方法,但返回了一条空消息

if (commandName === 'leaderboard') {
     let board = Tags.findAll({ limit: 10, attributes: ['user', 'catches']});
     lead = []
     lead.push(board)
     console.log(lead)
     await interaction.reply(
        codeBlock(
            lead.sort((a, b) => b.balance - a.balance)
                .filter(user => client.users.cache.has(user.user_id))
                .map((user, position) => `(${position + 1}) ${(user.tag)}: ${user.balance}`)
                .join("\n"),
            ),
    );
fsi0uk1n

fsi0uk1n1#

您忘记了等待findAll结果,因为它是异步的:

let board = await Tags.findAll({ limit: 10, attributes: ['user', 'catches']});
k75qkfdt

k75qkfdt2#

我通过SQLite向数据库请求而不是顺序化,从而找到了问题的解决方案

const SQLite = require('better-sqlite3')
const sql = SQLite('./database.sqlite')
...

board = []
    const top10 = await sql.prepare("SELECT * FROM tags ORDER BY catches DESC LIMIT 10;").all();
    top10.map(({ user, catches }) => {
        board.push(`${user} ${catches}`)
    });
    board = board.toString();
    board = board.replace(",", "\n")

    const embed = new EmbedBuilder()
        .setTitle("Leaderboard")
        .setColor(0x0099FF)
        .addFields({ name: '------------------', value: board});
    return interaction.reply({ embeds: [embed] });

相关问题