如何优化Sequelize中的包含?

时间:2019-03-22 15:16:17

标签: sequelize.js

我有下一个查询:

models.Transaction.findAll({
    where: {...},
    include: [
        {model: models.User, as: 'Seller'},
        {model: models.User, as: 'Buyer'},
        {model: models.User, as: 'Admin'},
        {model: models.PromoCode, include:[{
            model: models.User, as: 'Owner'
        }]}
    ],
    order: 'updated_at DESC'
})

结果我得到了查询:

SELECT .........
FROM "transactions" AS "Transaction" LEFT OUTER JOIN "users" AS "Seller" ON "Transaction"."seller_id" = "Seller"."id"
  LEFT OUTER JOIN "users" AS "Buyer" ON "Transaction"."buyer_id" = "Buyer"."id"
  LEFT OUTER JOIN "users" AS "Admin" ON "Transaction"."created_by_user_id" = "Admin"."id"
  LEFT OUTER JOIN "promo_codes" AS "PromoCode" ON "Transaction"."promo_code" = "PromoCode"."name"
  LEFT OUTER JOIN "users" AS "PromoCode.Owner" ON "PromoCode"."user_id" = "PromoCode.Owner"."id"
WHERE "Transaction"."is_ignore" = FALSE AND "Transaction"."state" = 1
ORDER BY "Transaction".updated_at DESC
LIMIT 50
OFFSET 0;

此查询速度很慢,因为要检索联接模型的所有属性。我想像这样优化此查询:

SELECT * FROM (SELECT *
FROM "transactions" AS "Transaction"
WHERE "Transaction"."is_ignore" = FALSE AND "Transaction"."state" = 1
ORDER BY "Transaction".updated_at DESC
LIMIT 50
OFFSET 0) AS "Transaction" 
  LEFT OUTER JOIN "users" AS "Seller" ON "Transaction"."seller_id" = "Seller"."id"
  LEFT OUTER JOIN "users" AS "Buyer" ON "Transaction"."buyer_id" = "Buyer"."id"
  LEFT OUTER JOIN "users" AS "Admin" ON "Transaction"."created_by_user_id" = "Admin"."id"
  LEFT OUTER JOIN "promo_codes" AS "PromoCode" ON "Transaction"."promo_code" = "PromoCode"."name"
  LEFT OUTER JOIN "users" AS "PromoCode.Owner" ON "PromoCode"."user_id" = "PromoCode.Owner"."id";

如何使用Sequelize查询生成器来做到这一点?

0 个答案:

没有答案