如何通过相同的搜索短语在数据库中搜索条目以查找两个单独的模型并参考sequelize?

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

我正在尝试在数据库中搜索发票。在服务器请求处理程序中我只有一件事:

searchPhrase
。因此,我必须通过发票的
invoice
以及通过引用嵌套在发票模型中的
serial number
来搜索
companyName

我现在搜索的代码是这样的:

const invoiceConditions = {
                userId: userId,
                [Op.or]: [{ serialCode: { [Op.like]: `%${searchPhrase}%` } }],
            };
            const foreignCompanyConditions = {
                [Op.or]: { companyName: { [Op.like]: `%${searchPhrase}%` } },
            }
            
            const allInvoices = await Invoice.findAll({
                where: invoiceConditions,
                include: [
                    { model: Company, as: "UserCompany" },
                    {
                        model: Company,
                        as: "ForeignCompany",
                        where: foreignCompanyConditions,
                    },
                    User,
                    Country,
                    Currency,
                ],
                order: [["createdAt", "DESC"]],
            });

现在我知道了

[Op.or]
是如何工作的,这可能是因为不同的模型中有两个单独的“[Op.or]”条件。但有没有办法让我的想法实现呢?如果是,非常感谢您的回答。预先感谢您。

我尝试嵌套公司价值观,这可能看起来很愚蠢,但有时确实有效。

mysql node.js express search sequelize.js
1个回答
0
投票

所以,我通过巧合找到了这个问题的答案 此代码有效:

            const invoiceConditions = {
                userId: userId,
                [Op.or]: [
                    { serialCode: { [Op.like]: `%${searchPhrase}%` } },
                    {
                        "$ForeignCompany.companyName$": { [Op.like]: `%${searchPhrase}%` },
                    },
                    {
                        "$ForeignCompany.companyCode$": { [Op.like]: `%${searchPhrase}%` },
                    },
                ],
            };

            const allInvoices = await Invoice.findAll({
                where: invoiceConditions,
                include: [
                    { model: Company, as: "UserCompany" },
                    {
                        model: Company,
                        as: "ForeignCompany",
                    },
                    User,
                    Country,
                    Currency,
                ],
                order: [["createdAt", "DESC"]],
            });
© www.soinside.com 2019 - 2024. All rights reserved.