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'
}]
})
You can add a where clause to the include itself.
This will return all Orders joined with Users which match with both clauses.