我有以下表格:Sequelize:多个where子句
文章 - 用户 - 标签 - 关注 - Suscribes
文章属于用户(FK:第一条表USERID)
文章可以有很多标签。这里是产生tagarticle表:
下面是追随者表:
而且Suscribes表:
用户可以按照许多用户并订阅国家(payId),标签或文章(用于notif ications)。
如何查询关于特定用户的所有关注用户和合适国家或标签的文章?
我有以下表格:Sequelize:多个where子句
文章 - 用户 - 标签 - 关注 - Suscribes
文章属于用户(FK:第一条表USERID)
文章可以有很多标签。这里是产生tagarticle表:
下面是追随者表:
而且Suscribes表:
用户可以按照许多用户并订阅国家(payId),标签或文章(用于notif ications)。
如何查询关于特定用户的所有关注用户和合适国家或标签的文章?
我假设你问Sequelize做查询的方式。 我不知道我是否正确理解你的问题。您正在寻找两个查询:
让我开始与模型之间进行的关联。
// in User model definition
User.belongsToMany(User, { as: 'Followers', through: 'Followers', foreignKey: 'userId', otherKey: 'followId' });
User.hasMany(Subscribe, { foreignKey: 'userId' });
User.hasMany(Article, { foreignKey: 'userId' });
随着使用上述协会,我们现在能够查询遵循用户的所有文章
models.User.findByPrimary(1, {
include: [
{
model: models.User,
as: 'Followers',
include: [ models.Article ]
}
]
}).then(function(user){
// here you have user with his followers and their articles
});
上面的查询如果您想查询的国家将产生类似
{
id: 1,
Followers: [
{
id: 4,
Articles: [
{
id: 1,
title: 'article title' // some example field of Article model
}
]
}
]
}
结果/ tag/article由特定用户订阅,则必须在Subscribe
模型中创建另一个关联
// in Subscribe model definition
Subscribe.belongsTo(Tag, { foreignKey: 'tagId' });
Subscribe.belongsTo(Article, { foreignKey: 'articleId' });
Subscribe.belongsTo(Country, { foreignKey: 'payId' });
现在我们要求所有的协会执行你问
models.User.findByPrimary(1, {
include: [
{
model: models.Subscribe,
include: [ models.Tag, models.Country, models.Article ]
}
]
}).then(function(user){
// here you get user with his subscriptions
});
在这个例子中,你得到用户用他的所有预订通过user.Subscribes
访问,这将有嵌套在第二个查询属性Tag
,Country
和Article
。如果用户订阅Tag
,则在这种情况下,Country
和Article
将为NULL
。
谢谢。这正是我需要的 –