Sequelize Eager加载嵌套错误

时间:2017-04-27 11:55:28

标签: sequelize.js

我的sql查询涉及四个表,(documentuserorganizationorganization_member(连接表)。这些表所涉及的关系如下如下:

用户到组织 User.belongsToMany(db.Organization, { through: 'organization_member', foreignKey: 'user_id'})

单位。用户 Organization.belongsToMany(db.User, { through: 'organization_member', foreignKey: 'organization_id'})

向用户提交文件 Document.belongsTo(db.User, { foreignKey: 'user_id'})

现在使用我的查询,我首先查询我的文档,按文档上的日期字段排序documentDate or document_date并限制10条记录。

models.Document.findAll({
        attributes: ['documentDate', 'title', 'discovery'],
        order: [[ sequelize.col('documentDate'), 'DESC']],
        limit: 10,
        ...
})

从那里开始,我包含了我的user模型,然后在user模型包含,organization模型和过滤(where子句)中嵌套仅属于组织中设置为会话的用户的那些文档。

models.Document.findAll({
    ...
    include: [{
                model: models.User,
                attributes: ['userId', 'firstName', 'lastName', 'picture'],
                include: [{
                    model: models.Organization,
                    where: { organizationId: req.session.organizationId },
                    attributes: ['organizationName']
                }]
            }]

})

此时,我收到错误消息:

Unhandled rejection SequelizeDatabaseError: column user.userid does not exist

这是奇怪的,因为该列存在userIduser_id

userId: {
        type: DataTypes.INTEGER,
        field:'user_id',
        autoIncrement: true,
        primaryKey: true
    },

当我把它扔进Postgres以查看错误的来源时,它是第25行。代码也在这里:https://pastebin.com/awsmEDfc

这可能是在include上使用where子句时发生的错误吗?

完整代码:

models.Document.findAll({
        attributes: ['documentDate', 'title', 'discovery'],
        order: [[ sequelize.col('documentDate'), 'DESC']],
        limit: 10,
        include: [{
            model: models.User,
            attributes: ['userId', 'firstName', 'lastName', 'picture'],
            include: [{
                model: models.Organization,
                where: { organizationId: req.session.organizationId },
                attributes: ['organizationName']
            }]
        }]
})

0 个答案:

没有答案