使用 Sequelize 将多个表中的多列聚合为单列
Aggregate multiple columns from multiple tables into single column with Sequelize
我正在处理 MTG 数据库,我正在尝试获取用户拥有的所有卡片的总价值我正在使用 Sequelize 和 Postgres。我有 4 个关联表:
Users
__
userId
Cards
__
cardId
CardPrices
___
cardId
usd
UserCard
__
userId
cardId
quantity
我可以进行查询并return所有具有相关价格的用户卡片,但我无法弄清楚如何将它们加在一起作为一个值并且return 它在查询中。我不确定这是否可行。
const userInventory = await db.User.findAll({
attributes: ['id', 'username'],
include: {
model: db.UserCard,
attributes: ['id'],
include: {
model: db.Card,
attributes: ['name'],
include: {
model: db.CardPrice,
attributes: ['usd', 'eur'],
as: 'prices'
}
}
},
});
returns:
[
{
"id": 1,
"username": "tyler",
"UserCards": [
{
"id": 1,
"quantity": 2,
"Card": {
"name": "Fury Sliver",
"prices": {
"usd": 0.42
}
}
},
{
"id": 2,
"quantity": 1,
"Card": {
"name": "Mystic Skyfish",
"prices": {
"usd": 0.07
}
}
}
]
}
]
在这个例子中,我希望实现 inventory_value
的 0.91
Sequelize 不用于执行复杂的聚合查询。您需要在 User.findAll
attributes
选项中使用普通 SQL 查询或至少一个 SQL 子查询,如下所示:
const userInventory = await db.User.findAll({
attributes: ['id', 'username',
[Sequelize.literal('(SELECT sum(UserCards.quantity*CardPrices.usd) from UserCards join CardPrices on (UserCards.cardId=CardPrices.cardId) where UserCards.userId=Users.id)'), 'inventory_value']],
...
我正在处理 MTG 数据库,我正在尝试获取用户拥有的所有卡片的总价值我正在使用 Sequelize 和 Postgres。我有 4 个关联表:
Users
__
userId
Cards
__
cardId
CardPrices
___
cardId
usd
UserCard
__
userId
cardId
quantity
我可以进行查询并return所有具有相关价格的用户卡片,但我无法弄清楚如何将它们加在一起作为一个值并且return 它在查询中。我不确定这是否可行。
const userInventory = await db.User.findAll({
attributes: ['id', 'username'],
include: {
model: db.UserCard,
attributes: ['id'],
include: {
model: db.Card,
attributes: ['name'],
include: {
model: db.CardPrice,
attributes: ['usd', 'eur'],
as: 'prices'
}
}
},
});
returns:
[
{
"id": 1,
"username": "tyler",
"UserCards": [
{
"id": 1,
"quantity": 2,
"Card": {
"name": "Fury Sliver",
"prices": {
"usd": 0.42
}
}
},
{
"id": 2,
"quantity": 1,
"Card": {
"name": "Mystic Skyfish",
"prices": {
"usd": 0.07
}
}
}
]
}
]
在这个例子中,我希望实现 inventory_value
的 0.91
Sequelize 不用于执行复杂的聚合查询。您需要在 User.findAll
attributes
选项中使用普通 SQL 查询或至少一个 SQL 子查询,如下所示:
const userInventory = await db.User.findAll({
attributes: ['id', 'username',
[Sequelize.literal('(SELECT sum(UserCards.quantity*CardPrices.usd) from UserCards join CardPrices on (UserCards.cardId=CardPrices.cardId) where UserCards.userId=Users.id)'), 'inventory_value']],
...