简体   繁体   中英

I created oneToMany relation but how I can get the single record belongs to the many record in Sequalize

Tagcategories Model

export const TagCategories = sequelize.define(
  "tag_categories",
  {
    categoryId: {
      type: DataTypes.INTEGER,
      field: "category_id",
      autoIncrement: true,
      primaryKey: true,
    },
    title: {
      type: DataTypes.STRING(50),
      field: "title",
      allowNull: false,
      unique: true,
    },

  },

);

TagCategories.hasMany(TagGroups, {
  foreignKey: "categoryId",
  sourceKey: "categoryId",
});
export default TagCategories;

TagGroups Model

export const TagGroups = sequelize.define(
  "tag_groups",
  {
    tagGroupId: {
      type: DataTypes.INTEGER,
      field: "tag_group_id",
      autoIncrement: true,
      primaryKey: true,
    },

    categoryId: {
      type: DataTypes.INTEGER,
      field: "category_id",
      allowNull: false,
    },

    title: {
      type: DataTypes.STRING(50),
      field: "title",
      allowNull: false,
      unique: true,
    },
  },
);

In the above models I establish oneToMany relationship between the TagCategories and TagGroups

But I want to fetch the record from the TagGroup table with the TagCategories details.

Thanks in advance

Did you look at examples in official documentation ?
Also, you need to add an association from TagGroups to TagCategories :

// there is no need to indicate `sourceKey` if this field is a primary key
TagGroups.belongsTo(TagCategories, {
  foreignKey: "categoryId",
});

It's better to define all associations in static functions and call all of them separately after all models will be registered. See the question and my answer here how to do it

In your case, the final request would be something like this

const tagGroup = await TagGroups.findOne({
  where: {
     tagGroupId: groupId
  },
  include: [{
     model: TagCategories
  }]
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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