Contents
  1. 1. [筆記] sequelize 自定義 snake_case table name
    1. 1.1. snake_case (underscore case)

[筆記] sequelize 自定義 snake_case table name

常用指令

  • Create Database
npx sequelize-cli db:create
npx sequelize-cli db:drop

  • Migrate Table
npx sequelize-cli db:migrate
npx sequelize-cli db:migrate:undo:all

  • Seed Data
npx sequelize-cli db:seed:all
npx sequelize-cli db:seed:undo:all

snake_case (underscore case)

以往設計資料庫欄位皆使用underscore_case,如果在sequelize使用

const sequelize = new Sequelize(
  config.database,
  config.username,
  config.password,
  {
    port: config.port,
    host: config.host,
    dialect: config.dialect,
    database: config.database,
    username: config.username,
    password: config.password,
    define: {
      timestamps: true,
      underscored: true,
      createdAt: "created_at",
      updatedAt: "updated_at",
    },
  }
);
"use strict";

module.exports = (sequelize, DataTypes) => {
  const Category = sequelize.define(
    "Category",
    {
      name: DataTypes.STRING,
      sub_name: DataTypes.STRING,
      index: DataTypes.NUMBER,
    },
    {
      tableName: "category",
      underscored: true,
    }
  );

  Category.associate = function (models) {
    // Category.hasOne(models.Image, {
    //   foreignKey: 'image_id'
    // });
    Category.belongsTo(models.Image, {
      foreignKey: {
        name: "image_id",
      },
      as: "image",
    });

    Category.hasMany(models.Product, {
      foreignKey: {
        name: "category_id",
      },
    });
  };

  return Category;
};

Comments