sequelize:无法在 DB 表中播种关联值 [英] sequelize : cannot seed association values in DB table

查看:14
本文介绍了sequelize:无法在 DB 表中播种关联值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 sequelize 将关联播种到我的数据库中,这些表是:用户和管理员.为此,我依赖论坛上的 这个答案.所以这是我的种子:

I am trying to seed an association into my db using sequelize, the tables being: Users and Admins. For this I am relying on this answer on the forum. so here is my seed:

'use strict';
const bcrypt = require('bcryptjs')
module.exports = {
    up: async (queryInterface, Sequelize) => {
        queryInterface.bulkInsert('Users', [{
            firstName: 'someone',
            lastName: 'awesome',
            email: 'someone@somewhere.com',
            password: bcrypt.hashSync('helloWorld', 8),
            type: 'admin',
            createdAt: new Date(),
            updatedAt: new Date()
        }], {});

        const users = await queryInterface.sequelize.query(
            'SELECT id from Users;'
        );

        return await queryInterface.bulkInsert('Admins', [{
            id: users[0].id,
            phone: '+9999999999',
            status: true, createdAt: new Date(),
            updatedAt: new Date()
        }]);
    },
    down: async (queryInterface) => {
        await queryInterface.bulkDelete('Admins', null, {});
        await queryInterface.bulkDelete('Users', null, {});
    }
};

现在,用户表中的数据已完美显示,但管理表仍为空

now, The data in user table is field up perfectly but the admin table remains empty

我尝试使用以下代码打印出 users[0].id:

I tried to print out the users[0].id with the following code:

const users = await queryInterface.sequelize.query(
    "SELECT id from Users"
);

console.log(users[0].id)

输出是未定义

但是数据再次被输入到表中!我知道这里发生了什么,但不知道如何解决!

but the data was once again fed to the table! I know what is happening here, but don't know how to resolve!

附:我还为 up 的第一个方法添加了等待,但这没有改变..

P.S. I also added await for the very first method of the up, but this changed nothing..

推荐答案

在查询用户之前,您不会等待用户插入结束,所以这样:

You are not waiting for the users insert to end before querying for them, so this:

const users = await queryInterface.sequelize.query(
   'SELECT id from Users;'
);

是空的,这个users[0].id一定是抛出了类型错误

Is empty, and this users[0].id must be throwing a type error

await 添加到您的第一个 queryInterface.bulkInsert 应该可以解决此问题

Adding an await to your first queryInterface.bulkInsert should fix that

await queryInterface.bulkInsert('Users', [{ // ...

这篇关于sequelize:无法在 DB 表中播种关联值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆