在 sequelize seed 中查找记录 [英] find records in sequelize seeds

查看:18
本文介绍了在 sequelize seed 中查找记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试为我的项目编写一些种子,但遇到了一些障碍.

I've been trying to write some seeds for my project, but I've ran into a bit of a snag.

我的 usersroles 表有 many-to-many 关系.因此,当我为数据库播种时,我需要在我的联接表中添加一条具有正确 ID 的记录.为此,我需要通过 email 查找用户并通过 name 查找角色并获取 ids ,这就是问题所在.我在 sequelize 网站 上找不到任何好的文档.我正在使用 sequelize-cli 进行播种和迁移.我得到一个 queryInterface 作为参数,但我找不到任何示例或提及这件事实际上可以做什么.只是一些简单的例子让我完成了迁移(不知何故)以及我在谷歌上能找到的东西.

I've got a many-to-many relation with my users and roles table. So, when I'm seeding the database I need to add a record with correct ids into my join table. In order to do that I need to find user by email and role by name and get the ids and that's the problem. I can't find any good documentation on the sequelize site. I'm using the sequelize-cli for the seeding and migrating things. I get as a parameter a queryInterface, but I can't find any example or mention what this thing can actually do. Just some simple examples just got me through the migrating (somehow) and what I was able to find on google.

我已经通过使用我会说的肮脏技巧"解决了这个问题......

I've resolved this by using a "dirty trick" I'd say...

// user_seeds.js
up: function (queryInterface, Sequelize) {
  return queryInterface.bulkInsert(table, [{
    id: 1,
    name: 'John doe',
    email: 'john@doe.com',
    created_at,
    updated_at
}], {});

// roles_seeds.js
up: function (queryInterface, Sequelize) {
  return queryInterface.bulkInsert(table, [{
    id: 1,
    name: 'admin',
    created_at,
    updated_at
  }, {
    id: 2,
    name: 'user',
    created_at,
    updated_at
}]);

//user_roles_seeds.js
up: function (queryInterface, Sequelize) {
    return queryInterface.bulkInsert(table, [{
    employee_id: 1,
    role_id: 1
  }]);
},

不喜欢这个解决方案,因为如果我想再次运行种子并忘记它是如何工作的,将来可能会很麻烦.我应该有一种方法可以使用这个 queryInterface 来查询数据库.我想知道你们中是否有人遇到过这个问题并解决了,如果有,请分享.

Don't like this solution since it may be troublesome in the future should I'd want to run the seeds again and forget about how this works. There should be a way for me to query the database using this queryInterface. I was wondering if one of you had ran into this issue and solved it, if so, please share.

推荐答案

是的,你可以使用queryInterface来查询数据库.

Yes you can use the queryInterface to query database.

  async up(queryInterface, Sequelize) {
    const user = await queryInterface.rawSelect('User', {
      where: {
        name: 'John doe',
      },
    }, ['id']);

    if(!user) {
       // do bulkInsert stuff.
    }
  },

这篇关于在 sequelize seed 中查找记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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