繁体   English   中英

与 MYSQL 续集的一对多关系

[英]One to many relationship in sequelize with MYSQL

我有两张桌子:

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
我们需要新的 model 作为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' });

暂无
暂无

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

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