简体   繁体   English

创建hasMany关联的元素

[英]Creating elements of a hasMany association

First time asking a Stack Overflow question so I hope I phrase it correctly: I'm trying to build a simple blog application as a homework assignment while using Sequelize for the database management. 第一次询问Stack Overflow问题所以我希望我正确地说出来:我正在尝试构建一个简单的博客应用程序作为家庭作业,同时使用Sequelize进行数据库管理。 However, I have a problem when trying to create some testdata when I try to create elements that are associated to my model. 但是,当我尝试创建与我的模型关联的元素时,尝试创建一些testdata时遇到问题。 Here is my code, it should be same syntax as in the documentation ( http://docs.sequelizejs.com/en/v3/docs/associations/#creating-elements-of-a-hasmany-or-belongstomany-association ). 这是我的代码,它应该与文档中的语法相同( http://docs.sequelizejs.com/en/v3/docs/associations/#creating-elements-of-a-hasmany-or-belongstomany-association ) 。

Current behavior: both users are created with all attributes, Posts are not created at all and no errors are given. 当前行为:使用所有属性创建两个用户,根本不创建帖子并且不给出错误。

masterdb.sync({force:true}).then( x => {
    return Promise.all([
        User.create({
            username:'Timothy',
            password:'plain-text',
            email:'x@msn.nl',
            Posts: [
                { body: 'Hello everyone, my name is Timothy.' },
                { body: 'Today was a good day.'}
            ]
        }, {
            include: [ Post ]
        }),
        User.create({
            username:'Jack Sparrow', 
            password:'plain-text', 
            email:'jacksparrow@msn.nl'
        }),
    ])
}).catch(x => console.log(x))

And here are my model and relations declarations: 以下是我的模型和关系声明:

const Sequelize = require('sequelize')
const masterdb = new Sequelize('blogapplication', process.env.POSTGRES_USER, process.env.POSTGRES_PASSWORD, {
    dialect: 'postgres',
})
const User = masterdb.define('user', {
    username: {
        type: Sequelize.STRING,
        unique: true,
        allowNull: false
    },
    password: {
        type: Sequelize.STRING,
        allowNull: false
    },
    email: {
        type: Sequelize.STRING,
        unique: true,
        allowNull: false
    }
}, {
    paranoid: true
})

const Post = masterdb.define('post', {
    body: {
        type: Sequelize.STRING(9001),
        allowNull: false,
        unique:true,
    }
}, {
    paranoid: true
})

User.hasMany(Post)

Fiddled around with your code and the following works. 摆弄你的代码和以下工作。 I don't know anything about Sequalize, so haven't got a clue if it should work like this. 我对Sequalize一无所知,所以不知道它是否应该像这样工作。 But it works :) 但它的工作原理:)

            posts: [
                { body: 'Hello everyone, my name is Timothy.' },
                { body: 'Today was a good day.'}
            ]

You had: 你有过:

        Posts: [
            { body: 'Hello everyone, my name is Timothy.' },
            { body: 'Today was a good day.'}
        ]

Do you see the difference? 你看得到差别吗?

I didn't either for a while, but you have a capital P and I have a lowercase p . 我没有一段时间,但你有一个大写P ,我有一个小写的p

Output: 输出:

testdb=# select * from users; 
 id |   username   |  password  |       email        |         createdAt          |         updatedAt          | deletedAt 
----+--------------+------------+--------------------+----------------------------+----------------------------+-----------
  1 | Jack Sparrow | plain-text | jacksparrow@msn.nl | 2016-11-17 22:38:06.493+01 | 2016-11-17 22:38:06.493+01 | 
  2 | Timothy      | plain-text | x@msn.nl           | 2016-11-17 22:38:06.492+01 | 2016-11-17 22:38:06.492+01 | 
(2 rows)

testdb=# select * from posts; 
 id |                body                 |         createdAt          |         updatedAt          | deletedAt | userId 
----+-------------------------------------+----------------------------+----------------------------+-----------+--------
  1 | Hello everyone, my name is Timothy. | 2016-11-17 22:38:06.515+01 | 2016-11-17 22:38:06.515+01 |           |      2
  2 | Today was a good day.               | 2016-11-17 22:38:06.515+01 | 2016-11-17 22:38:06.515+01 |           |      2
(2 rows)

Edit: I think I know why this has to be lower case. 编辑:我想我知道为什么这必须是小写的。

You defined post as follows: 您将帖子定义如下:

const Post = masterdb.define('post', {

If you want to do it your way you have to define it with a capital P . 如果你想以你的方式去做,你必须用大写P来定义它。

I think this is the cause of your problem because I tried to define the posts as Post and the key as post and then it doesn't work either. 我认为这是你问题的原因,因为我试图将帖子定义为Post ,将密钥定义为post ,然后它也不起作用。 Only when the definition and the key are the same it works. 只有当定义和密钥相同时才有效。

It's weird that in the docs of sequelize they do have a lowercase-capital letter irregularity like you do. 奇怪的是,在续集文档中,他们确实像你一样有一个小写大写字母不规则。 Could it be that they made a typo? 难道他们打错了吗? They also defined "tag" in lowercase t instead of uppercase T . 他们还用小写t而不是大写T定义“tag”。

I adapted your code so that it 'should work' with their tutorial code but it didn't. 我修改了你的代码,以便它“应该与他们的教程代码一起工作”,但事实并非如此。 It did work when I did my proposed change -- changing the lowercase letter in the definition to a capital letter. 当我完成提议的更改时它确实有效 - 将定义中的小写字母更改为大写字母。 However, they do have a slightly different manner in defining what a tag is. 但是,它们在定义标签的方式上确实有一些不同的方式。 They have var Tag = this.sequelize.definte('tag', { . 他们有var Tag = this.sequelize.definte('tag', {

Whereas you need to have var Tag = masterdb.define('tag', { . 而你需要var Tag = masterdb.define('tag', {

Could it be that their code also works due to this.sequelize ? 难道他们的代码也会因为this.sequelizethis.sequelize吗?

Here is your code with a working version of their tutorial code. 这是您的代码,其中包含其教程代码的工作版本。 I renamed the database to testdb and put a comment for the relevant line that I changed: 我将数据库重命名为testdb并对我更改的相关行发表评论:

const Sequelize = require('sequelize')
const masterdb = new Sequelize('testdb', process.env.POSTGRES_USER, process.env.POSTGRES_PASSWORD, {
    dialect: 'postgres',
})
const User = masterdb.define('user', {
    username: {
        type: Sequelize.STRING,
        unique: true,
        allowNull: false
    },
    password: {
        type: Sequelize.STRING,
        allowNull: false
    },
    email: {
        type: Sequelize.STRING,
        unique: true,
        allowNull: false
    }
}, {
    paranoid: true
})

var Tag = masterdb.define('Tag', { //this is 'tag' in their tutorial
  name: Sequelize.STRING
}, {
    paranoid: true
})

User.hasMany(Tag)

masterdb.sync({force:true}).then( x => {
    return Promise.all([
        User.create({
            username:'Timothy',
            password:'plain-text',
            email:'x@msn.nl',
            Tags: [
            { name: 'Alpha'},
            { name: 'Beta'}
          ]
        }, {
          include: [ Tag ]
        }),
        User.create({
            username:'Jack Sparrow', 
            password:'plain-text', 
            email:'jacksparrow@msn.nl'
        }),
    ])
}).catch(x => console.log(x))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM