排序用户遵循的帐户的显示提交

时间:2019-02-18 18:58:39

标签: javascript mysql node.js sequelize.js

我正在尝试找出查询用户关注的所有艺术家的作品的最佳方法。我知道这是一个多对多的关系,因此已经建立了我的表格,但我只是不知道如何正确查询这些提交内容。

用户可以关注多位艺术家,并且一旦关注,他就会看到所有这些艺术家的作品。

我的用户模型:

module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    id: DataTypes.INTEGER,
    username: DataTypes.STRING,
    mod: DataTypes.INTEGER
  }, {});
  User.associate = function(models) {
    // associations can be defined here
    User.belongsToMany(models.Artist, { through: models.UserArtist, foreignKey: 'userID', otherKey: 'artistID' })
  };
  return User;
};

我的艺术家模型:

module.exports = (sequelize, DataTypes) => {
  const Artist = sequelize.define('Artist', {
    id: DataTypes.INTEGER
    followers: DataTypes.INTEGER,
    imageURL: DataTypes.STRING,
    name: DataTypes.STRING,
    artistUID: DataTypes.STRING
  }, {});
  Artist.associate = function(models) {
    // associations can be defined here
    //artist can have many submissions
    Artist.hasMany(models.Submission, { foreignKey: 'artistID' });
    //artist belongs to many users that follow them
    Artist.belongsToMany(models.User, { through: models.UserArtist, as: 'artist', foreignKey: 'artistID', otherKey: 'userID' });
  };
  return Artist;
};

我的UserArtist加入表:

module.exports = (sequelize, DataTypes) => {
  const UserArtist = sequelize.define('UserArtist', {
    id: DataTypes.INTEGER,
    userID: DataTypes.INTEGER,
    artistID: DataTypes.INTEGER
  }, {});
  UserArtist.associate = function(models) {
    // associations can be defined here
  };
  return UserArtist;
};

最后,我的提交模型:

module.exports = (sequelize, DataTypes) => {
  const Submission = sequelize.define('Submission', {
    id: DataTypes.INTEGER
    releaseDate: DataTypes.STRING,
    title: DataTypes.STRING,
    artistID: DataTypes.INTEGER,
    userID: DataTypes.INTEGER
  }, {});
  Submission.associate = function(models) {
    // associations can be defined here
    //artist the submission belongs to
    Submission.belongsTo(models.Artist, { foreignKey: 'artistID' });
    //user the submission belongs to...a user can submit a submission
    Submission.belongsTo(models.User, { foreignKey: 'userID' });
  };
  return Submission;
};

现在如何正确查询用户关注的艺术家的作品? 我很近,但遇到了障碍。谢谢!

0 个答案:

没有答案