由于某种原因,他没有找到关联。我创建了关联,外键在postgres中完美创建。
user.js的
'use strict';
module.exports = app => {
const sequelize = app.db_connect.postgres.connect;
const Sequelize = app.db_connect.postgres.require;
const Reputation = app.models.reputation;
const Report = app.models.report;
const Group = app.models.group;
const Participant = app.models.participant;
const Topic = app.models.topic;
const Feed = app.models.feed;
const User = sequelize.define('user', {
//atributes
});
User.belongsToMany(User, { as: 'User', through: 'relationship', foreignKey: 'userId' });
User.belongsToMany(User, { as: 'Following', through: 'relationship', foreignKey: 'followingId' });
User.belongsToMany(Group, { as: 'Member', through: Participant, foreignKey: 'userId' });
User.hasMany(Report);
User.hasMany(Topic);
User.hasMany(Feed); //associate
return User;
}
feed.js
'use strict';
module.exports = app => {
const sequelize = app.db_connect.postgres.connect;
const Sequelize = app.db_connect.postgres.require;
const Report = app.models.report;
const Feed = sequelize.define('feed', {
//atributes
});
Feed.hasMany(Feed, {as: 'father'});
Feed.hasMany(Report)
return Feed;
}
呼叫:
const User = app.models.user;
const Sequelize = app.db_connect.postgres.require;
Feed.findOne({
include: User,
where: {
id: req.params.id
}
})
.then(result => res.json(result))
.catch(error => {
res.status(412).json({msg: error.message});
});
用户和Feed的关联关系为1:n。所以我使用了hasMany sequelize。
答案 0 :(得分:0)
因为你要查询Feed,而不是用户,你需要定义关联的“另一面”(反面):
Feed.belongsTo(User, {
as: 'User',
foreignKey: 'UserID' // or whatever your fk column is named for Feed -> User
});
请注意,当您调用Feed.findOne时,通常需要传递与您在关联上设置的值相同的as
值:
Feed.findOne({
include: {
model: User,
as: 'User' // must match the "as" from the defined association above
},
where: {
id: req.params.id
}
});