簡體   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