繁体   English   中英

包括一对多的关联范围

[英]Include one to many association in sequelize scope

我在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',
    },
  ]
}

我怎样才能做到这一点?

我知道我必须在用户模型的defaultScope选项中编写一些内容,但是呢?

实际的Users模型是:

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

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

首先更新模型:

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

而已。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM