mysql - 与 MYSQL Sequelize 的一对多关系

标签 mysql sql node.js sequelize.js

我有两个表:

const attr = {
  name: {
    type: DataTypes.STRING,
  },
};
const Tags = createModel('Tags', attr, {});
和:
const attr = {
  tagId: {
    type: DataTypes.INTEGER,
    references: { model: 'Tags', key: 'id' },
  }
}

const Client = createModel('Client', attr, {})
Client.belongsTo(Tag, { foreignKey: 'tagId', as: 'tags' });
我的查询是这样的:
const clientCount = await Client.findAll({
      include: [ { model: Tags, as: 'tags' } ],
      attributes: { exclude: 'tagId' }
    });
这是我的回应:
{
      "id": 1,
      "createdAt": "2020-01-20T00:00:00.000Z",
      "updatedAt": "2020-01-22T00:00:00.000Z",
      "tags": {
          "id": 1,
          "name": "New tag",
          "createdAt": "2020-01-20T00:00:00.000Z",
          "updatedAt": "2020-01-20T00:00:00.000Z"
        }
}
但我希望我的标签是一个数组,所以我必须定义一个一对多的关联,但到目前为止我尝试的一切都失败了。
我想要的是标签是一个数组,我可以在其中添加多个标签对象:
{
    "id": 1,
      "createdAt": "2020-01-20T00:00:00.000Z",
      "updatedAt": "2020-01-22T00:00:00.000Z",
      "tags": [
        {
          "id": 1,
          "name": "New tag",
          "createdAt": "2020-01-20T00:00:00.000Z",
          "updatedAt": "2020-01-20T00:00:00.000Z"
        }
  ]
}

最佳答案

方法1
我们需要新模型作为 Client_Tag

const attr = {
    clientId: {
        type: DataTypes.INTEGER,
    },
    tagId: {
        type: DataTypes.INTEGER,
    },
};
const Client_Tag = createModel('Client_Tag', attr, {});

Client.belongsToMany(Tag, {
    foreignKey: 'clientId',
    otherKey: 'tagId',
    through: models.Client_Tag,
    as: 'tags'
});
const clientCount = await Client.findAll({
      include: [ { model: Tags, as: 'tags' } ],
      attributes: { exclude: 'tagId' }
});
方法2
const attr = {
    name: {
        type: DataTypes.STRING,
    },
    clientId: { // need clientId in tag model, and remove 'tagId' from client model
        type: DataTypes.INTEGER,
    }
};
const Tags = createModel('Tags', attr, {});

Client.belongsToMany(Tag, { foreignKey: 'tagId', as: 'tags' });

关于mysql - 与 MYSQL Sequelize 的一对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65914068/

相关文章:

MySql - 查询如何编写嵌套条件?

php - 有没有更优雅的方法在 PHP 中格式化 MySQL 结果?

php - 使用 PHP 将时间戳转换为可读的日期/时间

php - php函数也会影响子目录吗?

javascript - 每个函数都应该是一个闭包吗?

php - MySQL - 在不同的查询中执行选择和删除?

sql - Postgresql错误: function "json_to_recordset(text) doesn' t exist"

sql - 选择今天日期的电话

node.js - Electronjs 和 Nodejs(Crypto) crypto.scryptSync 不是函数

javascript - Dialogue.Directive 不起作用 发出处理程序时?