【问题标题】:Sequelize.js joining an aliased assocation along with the non-aliased associationSequelize.js 与非别名关联一起加入别名关联
【发布时间】:2017-06-12 18:41:08
【问题描述】:

我有一个带有PostsUsers 的基本应用程序。我正在努力确保只向用户展示满足以下条件的帖子:

  1. 他们以前没有看过这篇文章
  2. 他们不是这篇文章的作者

为此,我有以下关联:

User.hasMany(Post, {
  foreignKey: 'user_id'
});

User.belongsToMany(Post, {
  as: {
    singular: 'ViewedPost',
    plural: 'ViewedPosts'
  },
  through: UserPostView,
  foreignKey: 'user_id',
  otherKey: 'post_id'
});

Post.belongsToMany(User, {
  as: {
    singular: 'ViewUser',
    plural: 'ViewUsers'
  },
  through: UserPostView,
  foreignKey: 'post_id',
  otherKey: 'user_id'
});

我可以通过单独的查询满足每个条件,但是,我希望能够通过单个查询返回满足我条件的帖子。

这是我现在用来获取用户以前没有看过的帖子的查询。如何修改此查询以同时返回非用户创作的帖子?

function fetchFreshPost(user) {
  return user.getViewedPosts({
    attributes: ['id'],
    joinTableAttributes: []
  }).then(function(posts) {
    var postIds = _.map(posts, 'id');
    var query = {
      limit: 1,
      where: {
        id: {
          $notIn: postIds
        }
      }
    };

    return Post.findAll(query);
  })
}

感谢您的宝贵时间。

【问题讨论】:

    标签: mysql sql join associations sequelize.js


    【解决方案1】:

    在你的 where 子句中,你可以添加 $ne,类似

    var query = {
          limit: 1,
          where: {
            id: {
              $notIn: postIds
            },
           user_id : {$ne : user.id}
          }
        };
    

    【讨论】:

    • 谢谢@Keval — 不幸的是,这仍然需要两个查询,一个是getViewedPosts 来获取用户查看过的帖子,然后是第二个使用 where 子句。我正在尝试将其合并到一个查询中。
    猜你喜欢
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-03
    • 1970-01-01
    相关资源
    最近更新 更多