【发布时间】:2017-06-12 18:41:08
【问题描述】:
我有一个带有Posts 和Users 的基本应用程序。我正在努力确保只向用户展示满足以下条件的帖子:
- 他们以前没有看过这篇文章
- 他们不是这篇文章的作者
为此,我有以下关联:
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