首页 > 解决方案 > 在 sequelize 范围内包含一对多关联

问题描述

sequelize在我的 node.js 应用程序中使用。

我有两个表:用户和图像。
用户表与图像是一对多的关系。因此,每个用户都可以拥有一个或多个图像。

       Users                         Images
+------+----------+  +------+-----------------------+--------+
|  id  |   name   |  |  id  |         url           | UserId |
+------+----------+  +------+-----------------------+--------+
| 123  | Markus   |  | 542  | https://et.ly/e2ts    | 123    |
| 456  | Thomas   |  | 731  | https://et.ly/dwas    | 123    |
+------+----------+  | 626  | https://et.ly/2w6i    | 456    |
                     +------+-----------------------+--------+

我想要一个范围,当我查询一个或多个用户时,我会得到这样的结果:

// Users.findById(123)
{
  id: 123,
  name: 'Markus',
  images: [
    {
      id: 542,
      url: 'https://et.ly/e2ts',
    },
    {
      id: 731,
      url: 'https://et.ly/dwas',
    },
  ]
}

我怎样才能做到这一点?

我知道我必须在我的 User 模型的 defaultScope 选项中写一些东西,但是什么?

实际Users模型是:

const Users = {
  name: 'Users',
  model: {
    schema: {
      id: { type: Sequelize.INTEGER, primaryKey: true, },
      name: { type: Sequelize.STRING },
    }
  options: {
    defaultScope: {
      // write scope here
    }
  }
}

标签: javascriptsequelize.js

解决方案


我已经知道该怎么做(真的很容易成为现实)

首先更新模型:

const Users = {
  name: 'Users',
  model: {
    schema: {
      id: { type: Sequelize.INTEGER, primaryKey: true, },
      name: { type: Sequelize.STRING },
    }
  options: {
    defaultScope: {
      include: [{
        model: Images, as: 'images' // LIKE THIS
      }]
    }
  }
}

然后在定义所有模型时定义关联:

Users.hasMany(Images, { as: 'images' });
Images.belongsTo(Users);

而已。


推荐阅读