简体   繁体   English

关联创建或更新

[英]sequelize create or update with association

i have a problem for add data on my db with sequelize. 我在使用sequelize在数据库上添加数据时遇到问题。

I have 2 tables with association howmany: 我有2个表与关联的数量:

const Price = sequelize.define('prices', {
      close: {
          type: Sequelize.INTEGER
      },
        open: {
            type: Sequelize.INTEGER
        },
        low: {
            type: Sequelize.INTEGER
        },
        high: {
            type: Sequelize.INTEGER
        },
      date: {
          type: Sequelize.DATE
      }
    });

const Crypto = sequelize.define('cryptos', {
      uuid: {
        type: Sequelize.UUID,
        defaultValue: Sequelize.UUIDV1,
        primaryKey: true
      },
      shortname: {
          type: Sequelize.STRING
      },
      name: {
          type: Sequelize.STRING
      },
        totalsupling:{
        type: Sequelize.STRING
        },
        imageurl:{
        type: Sequelize.STRING
        },
        prooftype:{
        type: Sequelize.STRING
        },
        premined:{
            type: Sequelize.STRING
        }
    });

db.cryptos.hasMany(db.price, {foreignKey: 'fk_cryptoid', sourceKey: 'uuid'}); db.cryptos.hasMany(db.price,{foreignKey:'fk_cryptoid',sourceKey:'uuid'}); db.price.belongsTo(db.cryptos, {foreignKey: 'fk_cryptoid', targetKey: 'uuid'}); db.price.belongsTo(db.cryptos,{foreignKey:'fk_cryptoid',targetKey:'uuid'}));

i can add new entries with : 我可以添加新条目:

Crypto.create({
    shortname: 'ETH',
    name: 'ethereum',
    totalsupling: 200000000,
    rank: 2,
    prices: [
        {
            close: '125',
                    open: '150',
                    high: '190',
                    low: '102'
            date: new Date()
        },
        {
            close: '125',
                    open: '150',
                    high: '190',
                    low: '102'
            date: new Date()
        }
    ]
}, {
    include: [ Price ]
}).then(() => {
    res.send("Done!");
})

But i can't add a new entity price with association in Crypto entity already existing : 但是我无法在已经存在的加密实体中添加具有关联的新实体价格:

Crypto.findOne({
    where: {uuid: 'f0a7e0e0-793d-11e8-b166-d7ecc2040fbe'},
    include: [ {model: Price }]
}).then(
    function (obj) {
       return obj.Price.updateAttributes(
                {
                    close: '125',
                    open: '150',
                    high: '190',
                    low: '102'
                }
                ).then(() => {
            console.log('done!!')
        })
    });

Message error : 讯息错误:

Unhandled rejection TypeError: Cannot read property 'updateAttributes' of undefined
at /home/blind/Documents/Init-Site-Info-Crypto/Controller/init.controller.js:65:29
at tryCatcher (/home/blind/Documents/Init-Site-Info-Crypto/node_modules/bluebird/js/release/util.js:16:23)
at Promise._settlePromiseFromHandler (/home/blind/Documents/Init-Site-Info-Crypto/node_modules/bluebird/js/release/promise.js:512:31)
at Promise._settlePromise (/home/blind/Documents/Init-Site-Info-Crypto/node_modules/bluebird/js/release/promise.js:569:18)
at Promise._settlePromise0 (/home/blind/Documents/Init-Site-Info-Crypto/node_modules/bluebird/js/release/promise.js:614:10)
at Promise._settlePromises (/home/blind/Documents/Init-Site-Info-Crypto/node_modules/bluebird/js/release/promise.js:693:18)
at Async._drainQueue (/home/blind/Documents/Init-Site-Info-Crypto/node_modules/bluebird/js/release/async.js:133:16)
at Async._drainQueues (/home/blind/Documents/Init-Site-Info-Crypto/node_modules/bluebird/js/release/async.js:143:10)
at Immediate.Async.drainQueues [as _onImmediate] (/home/blind/Documents/Init-Site-Info-Crypto/node_modules/bluebird/js/release/async.js:17:14)
at runCallback (timers.js:800:20)
at tryOnImmediate (timers.js:762:5)
at processImmediate [as _immediateCallback] (timers.js:733:5)

In you association, the crypto has many prices. 在您的协会中,加密货币有很多价格。 So, if you include your price model in the crypto, it should return an array of prices, and you can't do an updateAttributes in the array directly. 因此,如果您在加密货币中包含价格模型,则该价格模型应返回一个价格数组,并且您不能直接在该数组中执行updateAttributes。 That's one problem. 那是一个问题。 The other problem is that your code could not associate the tables. 另一个问题是您的代码无法关联表。

Try using an alias for your associations. 尝试为您的关联使用别名。 Something like this: 像这样:

db.cryptos.hasMany(db.price, {as: 'prices', foreignKey: 'fk_cryptoid', sourceKey: 'uuid'}); 
db.price.belongsTo(db.cryptos, {as: 'crypto', foreignKey: 'fk_cryptoid', targetKey: 'uuid'});

Then you can access like 然后您可以像访问

Crypto.findOne({
    where: {uuid: 'f0a7e0e0-793d-11e8-b166-d7ecc2040fbe'},
    include: [{model: Price, as: 'prices'}]
})
.then(function (prices) {
   console.log(prices)
})

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

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