【问题标题】:sequelize where relation is null续集关系为空
【发布时间】:2015-12-25 11:46:20
【问题描述】:

我对续集有疑问。这是我想要做的:

return pointsTransaction.findAndCountAll({
    where:{
        user_id: userId
    },
    limit: opts.limit,
    offset: opts.offset,
    include:[{
        model:sequelize.models.pointsPendingtransaction
    }]
});

生成的查询如下所示:

SELECT "pointsTransaction".*,
"pointsPendingtransactions"."transaction_ptr_id" AS "pointsPendingtransactions.transactionPtrId",
"pointsPendingtransactions"."is_active" AS "pointsPendingtransactions.isActive",
"pointsPendingtransactions"."transaction_id" AS "pointsPendingtransactions.transaction_id" 
FROM (
SELECT "pointsTransaction"."id",
"pointsTransaction"."date_time" AS "dateTime",
"pointsTransaction"."details",
"pointsTransaction"."points",
"pointsTransaction"."user_id" 
FROM "points_transaction" AS "pointsTransaction" 
WHERE "pointsTransaction"."user_id" = 10002 LIMIT 1000
) AS "pointsTransaction" 
LEFT OUTER JOIN "points_pendingtransaction" AS "pointsPendingtransactions" 
ON "pointsTransaction"."id" = "pointsPendingtransactions"."transaction_id"

因此,在 SQL 中,我只需在查询末尾添加该行即可:WHERE "pointsPendingtransactions"."transaction_id" IS null

所以我的问题是,我怎样才能用 sequelize 做到这一点?我尝试了许多不同的方法,但没有一种奏效......

【问题讨论】:

  • 类似的东西:include:[{ model:sequelize.models.pointsPendingtransaction, where:{transaction_id:null} }] 应该可以工作,尽管我自己没有尝试过
  • 我试过了,也尝试过一些基于计数的方法,但没有任何效果。我怀疑是由于“findAndCountAll”造成的错误
  • 您在尝试 Molda 的建议时遇到什么错误?
  • 我知道很晚了,但你可以在这里查看我的答案stackoverflow.com/questions/48005763/…

标签: node.js sequelize.js


【解决方案1】:

如果您使用的是 Sequelize.Op 中的 Sequelize 符号运算符,那么 ...

return pointsTransaction.findAndCountAll({
    where:{
        user_id: userId
    },
    limit: opts.limit,
    offset: opts.offset,
    include:[{
        model:sequelize.models.pointsPendingtransaction,
        where: {
            transaction_id: {
              // "$eq" changes to "[Op.eq]"
              [Op.eq]: null
            }
        }
    }]
});

【讨论】:

    【解决方案2】:

    尝试下一步

            where: {
                transaction_id: {
                  $eq: null
                }
            }
    

    生成IS NULL


    return pointsTransaction.findAndCountAll({
        where:{
            user_id: userId
        },
        limit: opts.limit,
        offset: opts.offset,
        include:[{
            model:sequelize.models.pointsPendingtransaction,
            where: {
                transaction_id: {
                  $eq: null
                }
            }
        }]
    });
    

    【讨论】:

    • 所有这一切都是在连接上添加一个额外的条件,它没有做他想要的。我自己试过了。在左外连接之后需要一个 where 子句,但在外部 where 子句中添加一个条件会将其添加到此部分 WHERE "pointsTransaction"."user_id" = 10002 LIMIT 1000
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-16
    • 2019-06-04
    • 2017-09-06
    • 2018-12-09
    • 2018-10-27
    • 1970-01-01
    • 2015-05-16
    相关资源
    最近更新 更多