Mysql 使用相同外键对多对多表进行续集只选择一个值
我的结构如下:Mysql 使用相同外键对多对多表进行续集只选择一个值,mysql,node.js,sequelize.js,Mysql,Node.js,Sequelize.js,我的结构如下: var User = sequelize.define('user', { name: DataTypes.STRING }); var Post = sequelize.define('post', { text: DataTypes.STRING }); var PostComment = sequelize.define('postComment ', { id: { type: DataTypes.BIGINT, primaryKey: t
var User = sequelize.define('user', {
name: DataTypes.STRING
});
var Post = sequelize.define('post', {
text: DataTypes.STRING
});
var PostComment = sequelize.define('postComment ', {
id: {
type: DataTypes.BIGINT,
primaryKey: true,
autoIncrement: true
},
comment: DataTypes.TEXT
});
Post.belongsToMany(User, {as: 'postUserComment', through: {model: models.PostComment, unique: false}, foreignKey: 'idPost'});
User.belongsToMany(Post, {through: {model: models.PostComment, unique: false}, foreignKey: 'idUserComment'});
我能够创建多个评论同一个用户的帖子
但是,如果我对同一用户的同一帖子有多条评论,并尝试通过以下操作选择它们:
Post.findAll({
include: [{model: models.User, as: 'postUserComment', attributes:['name'], through: {attributes: ['comment']}},
limit: 10,
offset: 0,
order: "id DESC"
...
它只会在帖子中为每个用户返回一条评论。我要怎么做才能全部选中它们
方言:mysql,
Sequelize版本:~3.27.0在Sequelize中,与
相关联的属于同一个ID是很棘手的
正如您已经注意到的,在和其他相关问题中,最好的方法是通过不同的关系来缓解它
例如,您可以添加:
Post.hasMany( models.PostComment, { foreignKey: 'idPost' } );
然后是你的问题
Post.findAll({
include: [
{model: models.User, as: 'postUserComment', attributes:['name'], through: {attributes: ['comment']}},
{model : models.PostComment}
],
limit: 10,
offset: 0,
order: "id DESC"
..
这不会更改您的数据库结构,并且会产生您想要的效果。当我尝试这样做时,在执行查询时会抛出一个错误:“Unhandled rejection TypeError:无法读取undefined的属性'getTableName'。但它适用于创建新实例我不好,这是一个语法错误,yout解决方案适用于我。谢谢