从子查询 Sequelize 引用主列

问题描述 投票:0回答:1

Customers 是表名,但我得到

“where 子句”中存在未知列“customers.id”

我已经尝试了所有可能的解决方案,甚至直接从文档中尝试。

const customers = await this.repository.findAndCountAll({
    where: condition,
    attributes: {
        // exclude: ['user_id', 'account_id', 'deletedAt'],
        include: [
            [
                Sequelize.literal(`(
                    SELECT SUM(amount)
                    FROM transactions
                    WHERE transactions.customer_id = customers.id
                    and transaction_type='PAYOUT'
                )`), 'totalDebit'
            ]
        ]
    },
    limit,
    offset,
    include: {
        association: 'groups',
        where: { id: groupId },
        through: { attributes: [] },
        attributes:[],
        required: true
    },
    order:[['createdAt', 'DESC']],
    raw: true,
});

return customers
nestjs sequelize.js sequelize-typescript
1个回答
0
投票

我能够解决这个问题,结果我需要使用为客户生成的别名sequelize,我必须记录查询并查看原始sql,然后使用别名而不是表名。万一以后有人遇到这个问题

 const customers = await this.repository.findAndCountAll({
            where: condition,
            attributes: {
                // exclude: ['user_id', 'account_id', 'deletedAt'],
                include: [
                    [
                        Sequelize.literal(`(
                            SELECT SUM(amount)
                            FROM transactions
                            WHERE transactions.customer_id = CustomerModel.id
                            and transaction_type='PAYOUT'
                        )`), 'totalDebit'
                    ]
                ]
            },
            limit,
            offset,
            include: {
                association: 'groups',
                where: { id: groupId },
                through: { attributes: [] },
                attributes:[],
                required: true
            },
            order:[['createdAt', 'DESC']],
            raw: true,
            logging: console.log,
        });
© www.soinside.com 2019 - 2024. All rights reserved.