Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
210 views
in Technique[技术] by (71.8m points)

sql - One to many relationship in sequelize with MYSQL

I have two tables:

const attr = {
  name: {
    type: DataTypes.STRING,
  },
};
const Tags = createModel('Tags', attr, {});

and:

const attr = {
  tagId: {
    type: DataTypes.INTEGER,
    references: { model: 'Tags', key: 'id' },
  }
}

const Client = createModel('Client', attr, {})
Client.belongsTo(Tag, { foreignKey: 'tagId', as: 'tags' });

and my query is this:

const clientCount = await Client.findAll({
      include: [ { model: Tags, as: 'tags' } ],
      attributes: { exclude: 'tagId' }
    });

and this is my response:

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

but I want my tags to be an array, so I guest I have to define a one to many association, but everything I tried so far failed.

What I want is tags to be an array, where I can add multiple tag objects: {

    "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"
        }
  ]
}
question from:https://stackoverflow.com/questions/65914068/one-to-many-relationship-in-sequelize-with-mysql

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...