简体   繁体   English

与 MYSQL 续集的一对多关系

[英]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"
        }
  ]
}

Method1方法1
We need new model as Client_Tag我们需要新的 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' }
});

Method2方法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