我有一个“评论”模型如下

var comment = sequelize.define('comment', {
    id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        allowNull: false,
        autoIncrement: true
    },
    author_openid:{
        type:  DataTypes.STRING,
        allowNull: false
    },
    text: { type:DataTypes.TEXT, allowNull:false }
});
model.sync();


一个“用户”模型如下

var model = sequelize.define('user', {
    id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        allowNull: false,
        autoIncrement: true
    },
    openid: {
        type:  DataTypes.STRING,
        allowNull: false
    }
});
model.sync();


然后关联如下

comment.belongsTo( user, { foreignKey:"author_openid", targetKey:"openid" } )
user.hasMany( comment, { foreignKey:"author_openid", sourceKey:"openid" } )


我想在上面的“用户”和“评论”之间建立关联,并按以下方式进行查询

user.findAll({
    include: [{
        model: comment
    }],
    raw: true
})


我的代码有什么问题?

最佳答案

快速浏览docs,看起来您的include应该只是模型而不是对象的数组。

const users = await user.findAll({
  include: [ comment ],
  raw: true
})

10-05 20:31
查看更多