New model was created at /home/admin/case/lib-backend/models/user.js . New migration was created at /home/admin/case/lib-backend/migrations/20230803111707-create-user.js .
--name 定義資料表名稱,建議使用小寫。
--underscored 欄位名稱都用小寫+底線 命名
--force 命名強制相同,不要有單複數 (在此都用單數)
在此要注意一下,產生的 model 是不是也是和我這次練習的 v6 版本一樣對於 force 沒有反應
sequelize 會產生下面原始碼
專案/migrations/20230803090103-create-user.js
(migrations 有提到修正方式,在此略過)
專案/models/user.js
'use strict'; const { Model } = require('sequelize'); module.exports = (sequelize, DataTypes) => { classuserextendsModel{ /** * Helper method for defining associations. * This method is not a part of Sequelize lifecycle. * The `models/index` file will call this method automatically. */ staticassociate(models) { // define association here } } user.init({ name: DataTypes.STRING, password: DataTypes.STRING }, { sequelize, modelName: 'user', underscored: true, freezeTableName: true, // 請手動加入這一行 }); return user; };
$ node main.js Executing (default): SELECT 1+1 AS result Executing (default): INSERT INTO `user` (`id`,`name`,`password`,`created_at`,`updated_at`) VALUES (?,?,?,?,?); Connection has been established successfully.
$ node main.js Executing (default): SELECT 1+1 AS result Executing (default): INSERT INTO `user` (`id`,`name`,`password`,`created_at`,`updated_at`) VALUES (?,?,?,?,?); 1, "chris", "chris", "2023-09-01 03:28:36", "2023-09-01 03:28:36" Connection has been established successfully.
棄用: getterMethods and setterMethods
DANGER
This feature has been removed in Sequelize 7.
You should consider using either VIRTUAL attributes or native class getter & setters instead.
$ node main.js Executing (default): SELECT 1+1 AS result newUser getSomething method: chris User associate Connection has been established successfully.
可以看見,如實的印出了 method 裡的字串,也透過 method 的 this 取得了實例的資料。
$ node main.js Executing (default): SELECT 1+1 AS result Executing (default): INSERT INTO `user` (`id`,`name`,`password`,`created_at`,`updated_at`) VALUES (DEFAULT,?,?,?,?); "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", "2023-09-01 03:45:09", "2023-09-01 03:45:09" Data too long for column 'name' at row 1