静态数据的 Sequelize 播种器

来源:undefined 2025-01-18 01:09:28 1048

关于如何在续集中进行播种的非常简短的帖子。 播种器是您在数据库中创建静态数据的方式,您希望这些数据无需用户创建即可显示。

这样做的目标是向此模型定义的待办事项应用程序中的非常基本的任务类型表添加一些静态数据:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

module.exports = (sequelize, sequelize) => {

const static_task_type = sequelize.define("static_task_type", {

id: {

type: sequelize.integer,

primarykey: true,

autoincrement: true

},

task_type: {

type: sequelize.string,

allownull: false

}

});

static_task_type.associate = function (models) {

};

return static_task_type;

};

登录后复制

创建播种模板:

1

npx sequelize-cli seed:generate --name add-static-task-types

登录后复制

这将使用几种任务类型填充播种模板。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

use strict;

/** @type {import(sequelize-cli).migration} */

module.exports = {

async up (queryinterface, sequelize) {

await queryinterface.bulkinsert(static_task_types,[

{ id: 1, task_type: deep ,createdat: new date(),updatedat: new date()},

{ id: 2, task_type: shallow ,createdat: new date(),updatedat: new date()},

{ id: 3, task_type: phone call ,createdat: new date(),updatedat: new date() },

{ id: 4, task_type: errands ,createdat: new date(),updatedat: new date()}]

)

},

async down (queryinterface, sequelize) {

await queryinterface.bulkdelete(static_task_types, null, {

truncate: true,

cascade: true, // optional: will also delete dependent rows if foreign keys are used

restartidentity: true, // optional: resets auto-increment counters

});

}

};

登录后复制

注意:不要忘记添加createdat和updatedat列,否则你会得到以下错误:

1

2

error: null value in column "createdat" of relation "static_urgencies" violates not-null constraint

error detail: failing row contains (1, now, null, null).

登录后复制

运行种子:

1

npx sequelize-cli db:seed:all

登录后复制

成功如dbeaver窗口所示:

以上就是静态数据的 Sequelize 播种器的详细内容,更多请关注php中文网其它相关文章!

最新文章