"user is not associated to feed!" 续集



由于某种原因,他没有找到关联。我创建了关联,外键在 postgres 中完美创建。

用户.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;
}

饲料.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});
    });

用户和源的关联为 1:N。所以我用了《有太多的续集》。

因为您查询的是 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
  }
});

最新更新