category.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // models/Category.js
  2. module.exports = (sequelize, DataTypes) => {
  3. const Category = sequelize.define('Category', {
  4. id: {
  5. type: DataTypes.INTEGER.UNSIGNED,
  6. primaryKey: true,
  7. autoIncrement: true
  8. },
  9. name: {
  10. type: DataTypes.STRING,
  11. allowNull: false,
  12. comment: '品类名称'
  13. },
  14. level: {
  15. type: DataTypes.INTEGER,
  16. defaultValue: 1,
  17. comment: '层级深度'
  18. },
  19. description: {
  20. type: DataTypes.TEXT,
  21. comment: '品类描述'
  22. },
  23. parentId: {
  24. type: DataTypes.INTEGER.UNSIGNED,
  25. allowNull: true,
  26. comment: '父级品类ID'
  27. },
  28. order: {
  29. type: DataTypes.INTEGER.UNSIGNED,
  30. defaultValue: 0,
  31. comment: '排序顺序'
  32. },
  33. isActive: {
  34. type: DataTypes.BOOLEAN,
  35. defaultValue: true,
  36. comment: '是否启用'
  37. }
  38. }, {
  39. tableName: 'categories',
  40. timestamps: true,
  41. indexes: [
  42. {
  43. fields: ['parentId']
  44. },
  45. {
  46. fields: ['name']
  47. }
  48. ]
  49. });
  50. // 添加associate方法
  51. Category.associate = function(models) {
  52. // 自关联关系
  53. Category.hasMany(Category, {
  54. as: 'children',
  55. foreignKey: 'parentId',
  56. onDelete: 'CASCADE'
  57. });
  58. Category.belongsTo(Category, {
  59. as: 'parent',
  60. foreignKey: 'parentId'
  61. });
  62. };
  63. return Category;
  64. };