【问题标题】:Sequelize Join Models Include many to manySequelize Join 模型包括多对多
【发布时间】:2017-04-15 06:09:22
【问题描述】:

假设我有三个这样的模型

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)

因此,1 个用户可以对多个酒吧进行多次 pubcrawl,以进行特定的 pub 抓取 我想找到“辛普森”去过的所有酒吧。

我需要更改模型定义吗?如果需要,请告诉我? findAll 查询会是什么样子?

【问题讨论】:

    标签: node.js sequelize.js


    【解决方案1】:

    如果我对你的数据库关系理解正确的话,可以这样表述:

    1 个用户可以访问多个酒吧
    许多用户可以访问 1 个栏

    因此,换句话说,用户和栏之间存在多对多关系,其中 JOIN 表是 UserPubCrawl。

    如果是这样,您的模型关联应如下所示:

    User.belongsToMany(Bar, { through: UserPubCrawl });
    Bar.belongsToMany(User, { through: UserPubCrawl });
    

    而且,找出辛普森去过的所有酒吧真的很简单:

    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
      }
    });
    

    【讨论】:

    • 太棒了。这正是我所需要的。谢谢@Adhyatmik
    • 如果您想找到所有访问过酒吧 X 和 Y 的用户怎么办?
    • @FelaMaslen User.findAll({ where: { user_id: '123' }, include: { model: Bars, where: {bar: X}, through: { attributes: [] } } } );
    • 通过:{ attributes: [] } 拯救我的一天。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-26
    • 1970-01-01
    • 1970-01-01
    • 2016-01-10
    • 1970-01-01
    • 2011-07-20
    • 1970-01-01
    相关资源
    最近更新 更多