0

I'm trying to make a search in a database for invoices. In the server request handler I have only one thing: searchPhrase. So I have to search invoice by serial number of the invoice, and also by companyName nested in invoice model by reference.

My code for searching now is this:

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"]],
            });

Now I get a little idea how [Op.or] works, it may be because there's two separate '[Op.or]' conditions in separate models. But is there a way to make my idea work? If yes, your answers are really appreciated. Thank you in advance.

I tried to nest company values which might seem stupid, but sometimes it works.

1 Answer 1

0

So, I found an answer to this question by coinsidence This code worked:

            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"]],
            });

Not the answer you're looking for? Browse other questions tagged or ask your own question.