te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>javascript - sequelize does not creating a table shows this result : "Executing (default): SELECT 1+1 AS result&quo
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - sequelize does not creating a table shows this result : "Executing (default): SELECT 1+1 AS result&quo

programmeradmin3浏览0评论

I try to create a table using sequelize it goes fine with no error but instead of creating a table is show this message as a result

Executing (default): SELECT 1+1 AS result

here my config file:

const Sequelize = require('sequelize');

const sequelize = new Sequelize('*******', '******', '*******', {
    dialect: 'mysql',
    host: 'localhost',
});

module.exports = sequelize;

here my user.js file:

const Sequelize = require('sequelize');

const sequelize = require('../db/mysql/config');

const User = sequelize.define('user', {
    id: {
        type: Sequelize.INREGER,
        autoIncrement: true,
        allowNull: false,
        primaryKey: true
    },
    userName: {
        type: Sequelize.STRING,
        allowNull: false
    },
    email: {
        type: Sequelize.STRING,
        allowNull: false
    },
    password: {
        type: Sequelize.STRING,
        allowNull: false
    }

});


module.exports = User;

and this is my test.js file i run it with node mend:

const sequelize = require('./db/mysql/config')

sequelize
    .sync()
    .then(result => {
        console.log(result);
    })
    .catch(err => {
        console.log(err);
    })

if I copy user.js code inside config file it works fine

I try to create a table using sequelize it goes fine with no error but instead of creating a table is show this message as a result

Executing (default): SELECT 1+1 AS result

here my config file:

const Sequelize = require('sequelize');

const sequelize = new Sequelize('*******', '******', '*******', {
    dialect: 'mysql',
    host: 'localhost',
});

module.exports = sequelize;

here my user.js file:

const Sequelize = require('sequelize');

const sequelize = require('../db/mysql/config');

const User = sequelize.define('user', {
    id: {
        type: Sequelize.INREGER,
        autoIncrement: true,
        allowNull: false,
        primaryKey: true
    },
    userName: {
        type: Sequelize.STRING,
        allowNull: false
    },
    email: {
        type: Sequelize.STRING,
        allowNull: false
    },
    password: {
        type: Sequelize.STRING,
        allowNull: false
    }

});


module.exports = User;

and this is my test.js file i run it with node mend:

const sequelize = require('./db/mysql/config')

sequelize
    .sync()
    .then(result => {
        console.log(result);
    })
    .catch(err => {
        console.log(err);
    })

if I copy user.js code inside config file it works fine

Share Improve this question edited Aug 27, 2020 at 8:30 sinammd asked Aug 27, 2020 at 8:09 sinammdsinammd 1321 gold badge1 silver badge9 bronze badges
Add a ment  | 

8 Answers 8

Reset to default 5

import your user.js model in config.js a example:-

     const User = require('enter your path here for user.js')

     User.sync();

Because you are not exporting the Tables you have created.

  • In your file you have created user.js, so you have to export it and make sure you are hitting(synchronizing) that table, either you can sync a particular table, or you can sync all the tables(models) at once.

How you can sync a Particular table (model)?

  • In your root file(which starts the application), you import the user.js

import user.js from ('your path to the file')

  • Now write modelName.sync();

How you can hit(sync) all the tables at once?

  1. After you created all the models, you have to export it
  2. Then in your root file, write the following

sequelize.sync()

once you import your model and require it into your controller, and then define your route, finishing by adding the route to the index.js or your app's entry point, the table will be created automatically, and no need to require the model directly into your entry point file meaning;

  • yourModel.js [export your model]
  • yourController.js [require your model here]
  • yourRoutes.js [require your controller]
  • index.js | app.js | main.js [require your router]
const sequelize = require('./db/mysql/config')

sequelize
    .sync()
    .then(result => {
        console.log(result);
    })
    .catch(err => {
        console.log(err);
    })

the path should be changed

const sequelize = require('./models/user')

import user.js not db-mysql-config.js

Importing user.js file to test.js solved the issue for me.

You need to execute your models somehow to create tables. You can do it by requiring your model files in a program execution flow.

My solution process : => Check database OWNER before

  1. Save all models files in /app/models
  2. Model example :
const {DataTypes, Model} = require('sequelize');

// on importe la connexion
const sequelize = require('./../database');

class User extends Model {
}

User.init({
        username: {
            type: DataTypes.STRING,
            allowNull: false
        },
        email: {
            type: DataTypes.STRING,
            allowNull: false,
            unique: true
        },
        password: {
            type: DataTypes.STRING,
            allowNull: false
        },
        roles: {
            type: DataTypes.JSON,
            defaultValue: {"roles":[{
                    "role_name":"ROLE_USER",
                }
            ]},
        },
        status: {
            type: DataTypes.BOOLEAN,
            defaultValue: false
        },
        birthday: {
            type: DataTypes.DATE,
            allowNull: false
        },
        filename: DataTypes.STRING,
        activation_token: DataTypes.STRING,

    },
    {
        underscored: true,
        sequelize, //connexion a l'instance
        timestamps: true,
        tableName: 'user'
    }
);

User.sync({ alter: true });
console.log("==> The table for the User model was just (re)created!");

module.exports = User;
  1. Create dedicated file for database connection in /app/database.js
const {Sequelize} = require('sequelize');

const sequelize = new Sequelize(process.env.PG_URL, {});

module.exports = sequelize;
  1. Create inside directory /app/models new file index.js
  2. Inside this file add all models required like that :
const User      = require('./user');
const Category  = require('./category');
    ...
module.exports = { User, Category };
  1. Create new file on project root like : init_models_db.js
const models = require('./app/models'); //By default load index.js inside /app/models
const sequelize = require('./app/database');

const init_BDD = async () => {
    try {
        await sequelize.authenticate();
        console.log('Connection has been established successfully.');
        const created =  sequelize.sync({force: true});

        if(created) {
            console.log("==> TABLE DONE !");
        }

    } catch (error) {
        console.error('Unable to connect to the database:', error);
    }
} 
init_BDD();
  1. Execute mand : node init_models_db.js
const Sequelize = require('sequelize');

const sequelize = new Sequelize('*******', '******', '*******', {
    dialect: 'mysql',
    host: 'localhost',
    logging: false

});

module.exports = sequelize;

You need to add 'logging: false' which solves the problem

Easy fix: Go to your controller file and instantiate your object

const User = require('models/user');

As soon as you create an instance for your model the tables will be generated.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论