包括一对多的关联范围

时间:2019-03-28 08:25:46

标签: javascript sequelize.js

我在自己的node.js应用中使用sequelize

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

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

1 个答案:

答案 0 :(得分:0)

我已经弄清楚该怎么做(真的很容易做到)

首先更新模型:

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

就是这样。

相关问题