gpt4 book ai didi

sequelize.js - 将子查询序列化为字段

转载 作者:行者123 更新时间:2023-12-03 21:02:59 25 4
gpt4 key购买 nike

我正在尝试通过 sequelized 生成这样的查询:

SELECT 
"Customers"."id",
(SELECT SUM("Orders"."amount") FROM "Orders"
WHERE "Orders"."CustomerId" = "Customers"."id") AS "totalAmount",
"Customer"."lastName" AS "Customer.lastName",
"Customer"."firstName" AS "Customer.firstName"
FROM "Customers" AS "Customer";

我试图避免 GROUP BY子句,因为我有很多字段要选择,而且我不想将它们全部分组(我认为它效率不高,不是吗?)

我已经尝试了几种通过 sequelize 实现它的方法,包括 {include: ...}{attributes: [[...]]} ,但没有任何运气。

有任何想法吗?或者我应该用一个大的 GROUP BY子句并让所有“常规”字段分组?

最佳答案

您最好的选择是:

    return Customer.findAll({
attributes: Object.keys(Customer.attributes).concat([
[sequelize.literal('(SELECT SUM("Orders"."amount") FROM "Orders" WHERE "Orders"."CustomerId" = "Customer"."id")'), 'totalAmount']
])
});

这看起来像是问题 #1869 的扩展:

Querying on the through model/join table is not possible currently unfortuneatly.



您的问题也与 this one 相关。 ,那里的问题有点像“为每个用户查询关联表”。

看着 test codeinclude条款我没有看到任何组选项,这是此功能缺乏证据。

解决方案:

当然,您可以只传递查询“raw”:
    return sequelize.query(
'SELECT *, (SELECT SUM("Orders"."amount") FROM "Orders" WHERE "Orders"."CustomerId" = "Customer"."id") AS "totalAmount" FROM "Customers" AS "Customer";',
Customer,
{raw: false}
);

这会给你想要的,并包装成 Customer实例。

或者,您可以添加一个返回另一个 promise 的实例方法:
instanceMethods: {
getOrderSummary: function () {
return Order.findAll({
where: {
CustomerId: this.id
},
attributes: [
[sequelize.fn('SUM', sequelize.col('amount')), 'sum'],
'CustomerId'],
group: ['CustomerId']
});
}
}

实例方法版本不是很干净,但它可以正常工作,并且根据您的情况可能更合适。

我发现的最佳解决方案是在 attribute 中使用 SQL 文字。查询的字段。唯一的缺点是它似乎在选择其他属性时把石板擦干净了,而 '*' 不会削减它。因此,您需要使用 Object.keys() 来解决此问题。 .
    return Customer.findAll({
attributes: Object.keys(Customer.attributes).concat([
[sequelize.literal('(SELECT SUM("Orders"."amount") FROM "Orders" WHERE "Orders"."CustomerId" = "Customer"."id")'), 'totalAmount']
])
});

尽管如此,它还是很有魅力,您可以将它用于一些更有趣的嵌套 SELECT。还有那个 findAll给了我们正确的:
Executing (default): SELECT "id", "firstName", "lastName", "createdAt", "updatedAt", (SELECT SUM("Orders"."amount") FROM "Orders" WHERE "Orders"."CustomerId" = "Customer"."id") AS "totalAmount" FROM "Customers" AS "Customer";
{ id: 1,
firstName: 'Test',
lastName: 'Testerson',
createdAt: Wed Feb 04 2015 08:05:42 GMT-0500 (EST),
updatedAt: Wed Feb 04 2015 08:05:42 GMT-0500 (EST),
totalAmount: 15 }
{ id: 2,
firstName: 'Invisible',
lastName: 'Hand',
createdAt: Wed Feb 04 2015 08:05:42 GMT-0500 (EST),
updatedAt: Wed Feb 04 2015 08:05:42 GMT-0500 (EST),
totalAmount: 99 }

顺便说一句,我也尝试向后做,并在 Order 上使用 GROUP BY型号选择进入 Customer模型,但这不起作用:
    // Doesn't work
return Order.findAll({
attributes: [
[Sequelize.fn('COUNT', '*'), 'orderCount'],
'CustomerId'
],
include: [
{model: Customer, attributes: ['id']}
],
group: ['CustomerId']
});

关于sequelize.js - 将子查询序列化为字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28286811/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com