问题描述
假设我有三个这样的模型
Say I have three models like this
var User = _define('user', {
username: Sequelize.INTEGER
});
var UserPubCrawl = _define('userpubcrawl', {
user_id: Sequelize.STRING(64), // the user
bar_id: Sequelize.INTEGER // 1 to many
});
var Bars = _define('bar', {
name: type: Sequelize.STRING,
}
感情是一顿饭
User(one) --> UserPubCrawl (to many) --> Bars(to many)
User(one) --> UserPubCrawl (to many) --> Bars(to many)
因此,1 个用户可以针对特定的 pub 爬网对许多条进行多次 pubcrawl我想找到辛普森"去过的所有酒吧.
So 1 user can have multiple pubcrawls to many bars for a particular pub crawlI want to find all the bars that "Simpson" went to.
我是否需要更改模型定义,如果需要,请告诉我?findAll 查询会是什么样子?
Do i need to change the model definitions, if so please show me?What would the findAll Query look like?
推荐答案
如果我理解你的数据库关系是正确的,它可以表述为:
If I understand your DB relationships right, it can be stated as:
1 个用户可以访问多个酒吧
1个酒吧可以被多个用户访问
1 user can visit many bars
1 bar can be visited by many users
因此,换句话说,用户和栏之间存在多对多关系,JOIN 表为 UserPubCrawl.
So, in other words you've a many to many relationship between Users and Bars, with the JOIN table being UserPubCrawl.
如果是这样,您的模型关联应如下所示:
If so, your model associations should look like:
User.belongsToMany(Bar, { through: UserPubCrawl });
Bar.belongsToMany(User, { through: UserPubCrawl });
而且,找出辛普森去过的所有酒吧,真的很简单:
And, finding out all the bars that Simpson went to, is really simple:
User.findAll({
where: { user_id: '123' },
include: {
model: Bars,
through: { attributes: [] } // this will remove the rows from the join table (i.e. 'UserPubCrawl table') in the result set
}
});
这篇关于Sequelize 连接模型包括多对多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!