“用户未关联到提要!”续集

Posted

技术标签:

【中文标题】“用户未关联到提要!”续集【英文标题】:"user is not associated to feed!" sequelizejs 【发布时间】:2016-07-17 20:10:22 【问题描述】:

由于某种原因,他没有找到关联。我创建了关联,外键在 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);
    );

用户和提要的关联为 1:n。所以我使用了hasMany sequelize。

【问题讨论】:

【参考方案1】:

因为您查询的是 Feed,而不是 User,所以您还需要定义关联的“另一面”(反向):

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
  
);

【讨论】:

以上是关于“用户未关联到提要!”续集的主要内容,如果未能解决你的问题,请参考以下文章

续集限制包括关联

如何通过关联查询续集模型,但包括所有关联对象?

用包含关联续集 findOrCreate

续集关联 On 或 ON

续集在关联模型上的位置

续集:如何为关联做等效的 findAndCountAll