Perform OR operation between two models in Sequelize

Asked

Viewed 63 times

0

In my Proposal table I have two Foreign Keys that reference the same table(Producer), I need to make a Where to check if there is a producer with a document equal to the searched in one of these Foreign Keys

Example:

     Proposta ->  id| nome_proposta | valor | produtor1 | produtor2 |
                   0| proposta vida | 12.00 |    0      |      1    |

     Produtor1 -> id| nome |documento
                   0| João | 12543    

     Produtor2 -> id| nome |documento
                   1| Lucas| 85476

Follow the Sequelize part:

where: {
                [Op.or]: {
                    {
                        model: Produtor,
                        as: "produtor1",
                        where: {
                            documento : documento_produtor,
                        },
                    },
                    {
                        model: Produtor,
                        as: "produtor2",
                        where: {
                            documento : documento_produtor,
                        },
                    },
                }
            }

Is there any way to perform this Select that would return the two producers of that proposal but only one had the same document? Why in my test I can only research one at a time.

Note: I have no way of knowing if the producer I want ta in the first or second Foreign key

  • I didn’t get it right. You want the Op.or function as "or exclusive" (xor)?

  • 1

    @Rafaeltavares It would be exclusive anyway, because document is a unique value. The point is that this OR does not work. And I don’t know how to do this OR with include

1 answer

1


I believe the problem with your query is that you didn’t put the Op.or as an array. Make the change and see if it works.

If it doesn’t work, I found a example query you specify directly within the where the column of an associated table:

{
    where: {
        [Op.or]: [
            { '$produtor1.documento$': documento_produtor },
            { '$produtor2.documento$': documento_produtor }
        ]
    },
    include: [
        {
            model: Produtor,
            as: "produtor1"
        },
        {
            model: Produtor,
            as: "produtor2"
        }
    ]
}
  • 1

    It worked out, thank you very much Rafael. The solution was to put this $ before and after the field.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.