登录
首页 >  文章 >  前端

静态数据的 Sequelize 播种器

来源:dev.to

时间:2024-12-28 11:19:11 354浏览 收藏

文章不知道大家是否熟悉?今天我将给大家介绍《静态数据的 Sequelize 播种器》,这篇文章主要会讲到等等知识点,如果你在看完本篇文章后,有更好的建议或者发现哪里有问题,希望大家都能积极评论指出,谢谢!希望我们能一起加油进步!

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

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

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;
  };

创建播种模板:

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

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

'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列,否则你会得到以下错误:

error: null value in column "createdat" of relation "static_urgencies" violates not-null constraint
error detail: failing row contains (1, now, null, null).

运行种子:

npx sequelize-cli db:seed:all

成功如dbeaver窗口所示:

image description

以上就是《静态数据的 Sequelize 播种器》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:dev.to 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>