sequelize 學習筆記

使用 eggjs 和 sequelize 進行開發,一些要注意的地方mysql

一、egg 的 egg-sequelize 插件是 sequelize 的V4版本,目前已經更新到V5版本,API有一些變化,好比V5沒有了findById等,須要注意。sql

二、配置時區,要將時區配置爲東八區,不然自動插入 created_at 字段的時候會是0時區的時間數據庫

  const sequelize = {
    dialect: 'mysql',
    host: '127.0.0.1',
    port: 3306,
    database: 'test',
    username: 'root',
    password: 'root',
    timezone: '+08:00',  // 配置時區
  };

三、數據庫建立表的時候必需要有 id, created_at, updated_at 三個字段,數據庫表名要使用複數形式,不如 user -> users,若是沒使用複數形式,在建立 model 的時候就要配置 freezeTableNameapp

    const User = app.model.define('user', {
        id: { type: INTEGER, primaryKey: true, autoIncrement: true },
        name: STRING(30),
        age: INTEGER,
    }, {
        freezeTableName: true, // Model 對應的表名將與model名相同
        // timestamps: false,  // 關閉 created_at 和 updated_at 字段
    });

四、new Date('2019-04-01') 查詢的是 2019-04-01 08:00:00 的時間,而不是0點,要想是0點須要 new Date('2019-04-01 00:00:00')spa

        const res = await ctx.model.User.findAll({
            where: {
                created_at: {
                    $lt: new Date(),  // 小於當前時間的
                    // $lt: new Date(new Date() - 1000 * 60 * 60 * 24 * 1),  // 小於當前時間一天前的
                    // $lt: new Date('2019-04-03'),  // 小於 2019-04-03 08:00:00
                    // $lt: new Date('2019-04-03 00:00:00'),  // 小於 2019-04-03 00:00:00
                    $gt: new Date(ctx.params.date)  // 接收到的日期字符串,如:2019-4-1
                }
            }
        });
相關文章
相關標籤/搜索