考虑此请求(针对Postgres)
var customers = await database.Customer.findAll({
attributes: [ 'idcustomer', 'firstname', 'lastname' ],
include: [
{
model: database.Telephone, as: "Telephones",
attributes: [ 'number' ],
where: { number: { [database.sequelize.Op.eq]: req.body.telephone } }
}
],
where: { [database.sequelize.Op.or]: [
{ firstname: { [database.sequelize.Op.iLike]: req.body.firstname} },
{ lastname: { [database.sequelize.Op.iLike]: req.body.lastname} },
{ email: { [database.sequelize.Op.iLike]: req.body.email } }
] }
});
我要实现的是通过名字和姓氏/电子邮件/电话号码查询客户,我们将其称为F,L,E和T。此查询基本上选择所有用户,其中T&(F | L | E)但是,我要尝试的是(F | L | E | T)。
代码过滤器中的参数where底部位于“客户”之前。参数,因此无法将数字与其余比较分组。有解决方法吗?
生成的SQL:
SELECT
"Customer"."idcustomer", "Customer"."firstname", "Customer"."lastname",
"Telephones"."number" AS "Telephones.number"
FROM "Customer" AS "Customer"
INNER JOIN "Telephone" AS "Telephones"
ON "Customer"."idcustomer" = "Telephones"."customer" AND "Telephones"."number" = ''
WHERE
("Customer"."firstname" ILIKE '' OR "Customer"."lastname" ILIKE '' OR "Customer"."email" ILIKE '');
答案 0 :(得分:2)
您可以使用Sequelize.col()引用包含的行:
var customers = await database.Customer.findAll({
attributes: [ 'idcustomer', 'firstname', 'lastname' ],
include: [
{
model: database.Telephone,
as: "Telephones",
attributes: [ 'number' ]
}
],
where: { [database.sequelize.Op.or]: [
{
telephone: Sequelize.where(Sequelize.col(`"Telephones".number`), {
[database.sequelize.Op.eq]: req.body.telephone
})
},
{ firstname: { [database.sequelize.Op.iLike]: req.body.firstname} },
{ lastname: { [database.sequelize.Op.iLike]: req.body.lastname} },
{ email: { [database.sequelize.Op.iLike]: req.body.email } }
] }
});