How to search for multiple fields in Association in sequalize?

23 Views Asked by At

I am making a searching feature for orders in eCommerce project. I need to search for order id and order.user.name.

const User = sequalize.define("user", {
    name: {type: DataTypes.STRING(64), allowNull: true},
    ...
})

const Order = sequalize.define("order", {
    id: {type: DataTypes.STRING, unique: true, allowNull: false, primaryKey: true}
})

User.hasMany(Order, {as: "user"})
Order.belongsTo(User)

I need to search for order.id OR order.user.name

This is what I got so far:

const query = "John"


 let whereClause = {}

        if (query) {
            whereClause = {
              [Op.or]: [
                {
                  id: {
                    [Op.like]: `%${query}%`
                  }
                },
                {
                  '$user.name$': {
                    [Op.like]: `%${query}%`
                  }
                }
              ]
            }
          }


            const orders = await models.Order.findAll({
                where: whereClause,
                include: [{
                    model: models.User,
                    as: 'user' 
                }]
            })

The ERROR I am getting over and over is:

missing FROM-clause entry for table "user"

UPDATED:

Problem is solved.

 let whereClause = {}

        if (search) {
            whereClause = {
                [Op.or]: [{
                        id: {
                            [Op.iLike]: `%${search}%`,
                        },
                    },
                    {
                        '$user.name$': {
                            [Op.iLike]: `%${search}%`,
                        },
                    },
                ]
            }
        }

    const orders = await models.Order.findAll({
                where: whereClause,
                include: [{
                    model: models.User,
                    as: 'user'
                }]
            })

1

There are 1 best solutions below

1
db3000 On

You can add a where clause to the include itself.

        const orders = await models.Order.findAll({
            where: {id: idYouLookFor},
            include: [{
                model: models.User,
                as: 'user',
                where: { name: "nameYouLookFor" }
            }]
        })

This will return all Orders joined with Users which match with both clauses.