如何添加belongsToMany关系Sequelize?

时间:2016-07-08 16:38:13

标签: angularjs node.js express sequelize.js mean

我有3个型号,Product,Age和ProductAges

product.js

'use strict';

module.exports = function(sequelize, DataTypes){

    var Product = sequelize.define('Product', {
        sku: DataTypes.STRING,
        name: DataTypes.STRING,
        value: DataTypes.STRING,
        body: DataTypes.TEXT
    }, {
        associate: function(models) {
            Product.belongsToMany(models.Age, {through: models.ProductAges});
        }
    });

    return Product;
}

age.js

'use strict';

module.exports = function(sequelize, DataTypes) {

    var Age = sequelize.define('Age', {
            name: DataTypes.STRING,
            value: DataTypes.STRING
    },{
        associate: function(models) {
            Age.belongsToMany(models.Product, {through: models.ProductAges})
        }
    }
    );

    return Age;
};

产品age.js

'use strict';

module.exports = function(sequelize, DataTypes){

    var ProductAges = sequelize.define('ProductAges', {
        id: {
            type: DataTypes.INTEGER,
            primaryKey: true,
            autoIncrement: true
        }
    });

    return ProductAges;
}

在Create函数中,在产品控制器中:

exports.create = function(req, res){
    // save and return and instance of product on the res object
    console.log('Request Body ==> ', req.body);
    // { 
    //     sku: '123',
    //     name: 'ប៉ោម',
    //     value: 'Apple',
    //     body: 'ល្អណាស់',
    //     ages:[{ 
    //         id: 1,
    //         name: 'តិចជាង ១៩ ឆ្នាំ',
    //         value: 'less_than_19',
    //         createdAt: '2016-07-08T12:47:06.000Z',
    //         updatedAt: '2016-07-08T13:10:10.000Z',
    //         ticked: true 
    //     },{
    //         id: 3,
    //         name: 'ចន្លោះ ២០ ទៅ ២៤ ឆ្នាំ',
    //         value: 'between_20_24',
    //         createdAt: '2016-07-08T12:59:05.000Z',
    //         updatedAt: '2016-07-08T12:59:05.000Z',
    //         ticked: true
    //     }] 
    // }

    db.Product.create(req.body).then(function(product){
        if (!product){
            return res.send('user/signup', {errors: new StandardError('Product could not be created')});
        }
        else{
            return res.jsonp(product);
        }
    }).catch(function(err){
        return res.send('users/signup', {
             error: err,
             status: 500
        })
    })
};

这只是为了插入产品而工作正常。但是,我还想根据Sequelize Docs here使用'addAges'函数插入ProductAges模型。

所以,我将create function controller修改为:

exports.create = function(req, res){
    // save and return and instance of product on the res object

    db.Product.create(req.body).then(function(product){
        if (!product){
            return res.send('user/signup', {errors: new StandardError('Product could not be created')});
        }
        else{
            db.Product.addAges(req.body.ages);
            return res.jsonp(product);
        }
    }).catch(function(err){
        return res.send('users/signup', {
             error: err,
             status: 500
        })
    })
};

我收到了这个错误日志:

verbose: Executing (default): SELECT `data` FROM `Sessions` AS `Session` WHERE `Session`.`sid` = 'Qzad_nN3rMR2RrsZ-Oa3H4A5BfL2optm' LIMIT 1;
    verbose: Executing (default): SELECT `id`, `name`, `email`, `username`, `hashedPassword`, `provider`, `salt`, `facebookUserId`, `twitterUserId`, `twitterKey`, `twitterSecret`, `github`, `openId`, `createdAt`, `updatedAt` FROM `Users` AS `User` WHERE `User`.`id` = 1;
    info: Session: { id: 1, username: john }
    verbose: Executing (default): INSERT INTO `Products` (`id`,`sku`,`name`,`value`,`body`,`createdAt`,`updatedAt`) VALUES (DEFAULT,'123','ប៉ោម','Apple','ល្អណាស់','2016-07-08 16:26:44','2016-07-08 16:26:44');
    Fri, 08 Jul 2016 16:26:44 GMT express deprecated res.send(status, body): Use res.status(status).send(body) instead at app/controllers/products.js:45:20
    verbose: Executing (default): SELECT `id`, `sid`, `data`, `createdAt`, `updatedAt` FROM `Sessions` AS `Session` WHERE `Session`.`sid` = 'Qzad_nN3rMR2RrsZ-Oa3H4A5BfL2optm' LIMIT 1;
    Unhandled rejection RangeError: Invalid status code: 0
        at ServerResponse.writeHead (_http_server.js:192:11)
        at ServerResponse.writeHead (/Users/Roller/Working/Web/ponds_web/node_modules/on-headers/index.js:55:19)
        at ServerResponse.writeHead (/Users/Roller/Working/Web/ponds_web/node_modules/on-headers/index.js:55:19)
        at ServerResponse.writeHead (/Users/Roller/Working/Web/ponds_web/node_modules/on-headers/index.js:55:19)
        at ServerResponse._implicitHeader (_http_server.js:157:8)
        at ServerResponse.write (/Users/Roller/Working/Web/ponds_web/node_modules/compression/index.js:83:14)
        at writetop (/Users/Roller/Working/Web/ponds_web/node_modules/express-session/index.js:286:26)
        at ServerResponse.end (/Users/Roller/Working/Web/ponds_web/node_modules/express-session/index.js:328:16)
        at ServerResponse.send (/Users/Roller/Working/Web/ponds_web/node_modules/express/lib/response.js:205:10)
        at ServerResponse.json (/Users/Roller/Working/Web/ponds_web/node_modules/express/lib/response.js:250:15)
        at ServerResponse.send (/Users/Roller/Working/Web/ponds_web/node_modules/express/lib/response.js:152:21)
        at .<anonymous> (/Users/Roller/Working/Web/ponds_web/app/controllers/products.js:45:20)
        at tryCatcher (/Users/Roller/Working/Web/ponds_web/node_modules/bluebird/js/release/util.js:16:23)
        at Promise._settlePromiseFromHandler (/Users/Roller/Working/Web/ponds_web/node_modules/bluebird/js/release/promise.js:504:31)
        at Promise._settlePromise (/Users/Roller/Working/Web/ponds_web/node_modules/bluebird/js/release/promise.js:561:18)
        at Promise._settlePromise0 (/Users/Roller/Working/Web/ponds_web/node_modules/bluebird/js/release/promise.js:606:10)
    Unhandled rejection RangeError: Invalid status code: 0
        at ServerResponse.writeHead (_http_server.js:192:11)
        at ServerResponse.writeHead (/Users/Roller/Working/Web/ponds_web/node_modules/on-headers/index.js:55:19)
        at ServerResponse.writeHead (/Users/Roller/Working/Web/ponds_web/node_modules/on-headers/index.js:55:19)
        at ServerResponse.writeHead (/Users/Roller/Working/Web/ponds_web/node_modules/on-headers/index.js:55:19)
        at ServerResponse._implicitHeader (_http_server.js:157:8)
        at ServerResponse.end (/Users/Roller/Working/Web/ponds_web/node_modules/compression/index.js:102:14)
        at writeend (/Users/Roller/Working/Web/ponds_web/node_modules/express-session/index.js:257:22)
        at onsave (/Users/Roller/Working/Web/ponds_web/node_modules/express-session/index.js:325:11)
        at .<anonymous> (/Users/Roller/Working/Web/ponds_web/node_modules/express-sequelize-session/lib/e4store.js:90:51)
        at tryCatcher (/Users/Roller/Working/Web/ponds_web/node_modules/bluebird/js/release/util.js:16:23)
        at Promise._settlePromiseFromHandler (/Users/Roller/Working/Web/ponds_web/node_modules/bluebird/js/release/promise.js:504:31)
        at Promise._settlePromise (/Users/Roller/Working/Web/ponds_web/node_modules/bluebird/js/release/promise.js:561:18)
        at Promise._settlePromise0 (/Users/Roller/Working/Web/ponds_web/node_modules/bluebird/js/release/promise.js:606:10)
        at Promise._settlePromises (/Users/Roller/Working/Web/ponds_web/node_modules/bluebird/js/release/promise.js:681:18)
        at Async._drainQueue (/Users/Roller/Working/Web/ponds_web/node_modules/bluebird/js/release/async.js:138:16)
        at Async._drainQueues (/Users/Roller/Working/Web/ponds_web/node_modules/bluebird/js/release/async.js:148:10)
    error:  RangeError: Invalid status code: 0
        at ServerResponse.writeHead (_http_server.js:192:11)
        at ServerResponse.writeHead (/Users/Roller/Working/Web/ponds_web/node_modules/on-headers/index.js:55:19)
        at ServerResponse.writeHead (/Users/Roller/Working/Web/ponds_web/node_modules/on-headers/index.js:55:19)
        at ServerResponse.writeHead (/Users/Roller/Working/Web/ponds_web/node_modules/on-headers/index.js:55:19)
        at ServerResponse._implicitHeader (_http_server.js:157:8)
        at ServerResponse.end (/Users/Roller/Working/Web/ponds_web/node_modules/compression/index.js:102:14)
        at writeend (/Users/Roller/Working/Web/ponds_web/node_modules/express-session/index.js:257:22)
        at onsave (/Users/Roller/Working/Web/ponds_web/node_modules/express-session/index.js:325:11)
        at .<anonymous> (/Users/Roller/Working/Web/ponds_web/node_modules/express-sequelize-session/lib/e4store.js:88:51)
        at tryCatcher (/Users/Roller/Working/Web/ponds_web/node_modules/bluebird/js/release/util.js:16:23)
        at Promise._settlePromiseFromHandler (/Users/Roller/Working/Web/ponds_web/node_modules/bluebird/js/release/promise.js:504:31)
        at Promise._settlePromise (/Users/Roller/Working/Web/ponds_web/node_modules/bluebird/js/release/promise.js:561:18)
        at Promise._settlePromise0 (/Users/Roller/Working/Web/ponds_web/node_modules/bluebird/js/release/promise.js:606:10)
        at Promise._settlePromises (/Users/Roller/Working/Web/ponds_web/node_modules/bluebird/js/release/promise.js:685:18)
        at Async._drainQueue (/Users/Roller/Working/Web/ponds_web/node_modules/bluebird/js/release/async.js:138:16)
        at Async._drainQueues (/Users/Roller/Working/Web/ponds_web/node_modules/bluebird/js/release/async.js:148:10)
    Warning: Unexpected block "main"  on line 3 of /Users/Roller/Working/Web/ponds_web/app/views/500.jade. This block is never used. This warning will be an error in v2.0.0

然后,我尝试使用Promise:

exports.create = function(req, res){
    // save and return and instance of product on the res object

    db.Product.create(req.body).then(function(product){
        if (!product){
            return res.send('user/signup', {errors: new StandardError('Product could not be created')});
        }
        else{
            db.Product.addAges(ages).then(function(){
                return res.jsonp(product);
            });
        }
    }).catch(function(err){
        return res.send('users/signup', {
             error: err,
             status: 500
        })
    })
};

然后我收到了这个错误:

verbose: Executing (default): SELECT `data` FROM `Sessions` AS `Session` WHERE `Session`.`sid` = 'Qzad_nN3rMR2RrsZ-Oa3H4A5BfL2optm' LIMIT 1;
    verbose: Executing (default): SELECT `id`, `name`, `email`, `username`, `hashedPassword`, `provider`, `salt`, `facebookUserId`, `twitterUserId`, `twitterKey`, `twitterSecret`, `github`, `openId`, `createdAt`, `updatedAt` FROM `Users` AS `User` WHERE `User`.`id` = 1;
    info: Session: { id: 1, username: john }
    verbose: Executing (default): INSERT INTO `Products` (`id`,`sku`,`name`,`value`,`body`,`createdAt`,`updatedAt`) VALUES (DEFAULT,'123','ប៉ោម','Apple','ល្អណាស់','2016-07-08 16:30:17','2016-07-08 16:30:17');
    verbose: Executing (default): SELECT `id`, `sid`, `data`, `createdAt`, `updatedAt` FROM `Sessions` AS `Session` WHERE `Session`.`sid` = 'Qzad_nN3rMR2RrsZ-Oa3H4A5BfL2optm' LIMIT 1;
    Unhandled rejection RangeError: Invalid status code: 0
        at ServerResponse.writeHead (_http_server.js:192:11)
        at ServerResponse.writeHead (/Users/Roller/Working/Web/ponds_web/node_modules/on-headers/index.js:55:19)
        at ServerResponse.writeHead (/Users/Roller/Working/Web/ponds_web/node_modules/on-headers/index.js:55:19)
        at ServerResponse.writeHead (/Users/Roller/Working/Web/ponds_web/node_modules/on-headers/index.js:55:19)
        at ServerResponse._implicitHeader (_http_server.js:157:8)
        at ServerResponse.write (/Users/Roller/Working/Web/ponds_web/node_modules/compression/index.js:83:14)
        at writetop (/Users/Roller/Working/Web/ponds_web/node_modules/express-session/index.js:286:26)
        at ServerResponse.end (/Users/Roller/Working/Web/ponds_web/node_modules/express-session/index.js:328:16)
        at ServerResponse.send (/Users/Roller/Working/Web/ponds_web/node_modules/express/lib/response.js:205:10)
        at ServerResponse.json (/Users/Roller/Working/Web/ponds_web/node_modules/express/lib/response.js:250:15)
        at ServerResponse.send (/Users/Roller/Working/Web/ponds_web/node_modules/express/lib/response.js:152:21)
        at .<anonymous> (/Users/Roller/Working/Web/ponds_web/app/controllers/products.js:46:20)
        at tryCatcher (/Users/Roller/Working/Web/ponds_web/node_modules/bluebird/js/release/util.js:16:23)
        at Promise._settlePromiseFromHandler (/Users/Roller/Working/Web/ponds_web/node_modules/bluebird/js/release/promise.js:504:31)
        at Promise._settlePromise (/Users/Roller/Working/Web/ponds_web/node_modules/bluebird/js/release/promise.js:561:18)
        at Promise._settlePromise0 (/Users/Roller/Working/Web/ponds_web/node_modules/bluebird/js/release/promise.js:606:10)
    Unhandled rejection RangeError: Invalid status code: 0
        at ServerResponse.writeHead (_http_server.js:192:11)
        at ServerResponse.writeHead (/Users/Roller/Working/Web/ponds_web/node_modules/on-headers/index.js:55:19)
        at ServerResponse.writeHead (/Users/Roller/Working/Web/ponds_web/node_modules/on-headers/index.js:55:19)
        at ServerResponse.writeHead (/Users/Roller/Working/Web/ponds_web/node_modules/on-headers/index.js:55:19)
        at ServerResponse._implicitHeader (_http_server.js:157:8)
        at ServerResponse.end (/Users/Roller/Working/Web/ponds_web/node_modules/compression/index.js:102:14)
        at writeend (/Users/Roller/Working/Web/ponds_web/node_modules/express-session/index.js:257:22)
        at onsave (/Users/Roller/Working/Web/ponds_web/node_modules/express-session/index.js:325:11)
        at .<anonymous> (/Users/Roller/Working/Web/ponds_web/node_modules/express-sequelize-session/lib/e4store.js:90:51)
        at tryCatcher (/Users/Roller/Working/Web/ponds_web/node_modules/bluebird/js/release/util.js:16:23)
        at Promise._settlePromiseFromHandler (/Users/Roller/Working/Web/ponds_web/node_modules/bluebird/js/release/promise.js:504:31)
        at Promise._settlePromise (/Users/Roller/Working/Web/ponds_web/node_modules/bluebird/js/release/promise.js:561:18)
        at Promise._settlePromise0 (/Users/Roller/Working/Web/ponds_web/node_modules/bluebird/js/release/promise.js:606:10)
        at Promise._settlePromises (/Users/Roller/Working/Web/ponds_web/node_modules/bluebird/js/release/promise.js:681:18)
        at Async._drainQueue (/Users/Roller/Working/Web/ponds_web/node_modules/bluebird/js/release/async.js:138:16)
        at Async._drainQueues (/Users/Roller/Working/Web/ponds_web/node_modules/bluebird/js/release/async.js:148:10)
    error:  RangeError: Invalid status code: 0
        at ServerResponse.writeHead (_http_server.js:192:11)
        at ServerResponse.writeHead (/Users/Roller/Working/Web/ponds_web/node_modules/on-headers/index.js:55:19)
        at ServerResponse.writeHead (/Users/Roller/Working/Web/ponds_web/node_modules/on-headers/index.js:55:19)
        at ServerResponse.writeHead (/Users/Roller/Working/Web/ponds_web/node_modules/on-headers/index.js:55:19)
        at ServerResponse._implicitHeader (_http_server.js:157:8)
        at ServerResponse.end (/Users/Roller/Working/Web/ponds_web/node_modules/compression/index.js:102:14)
        at writeend (/Users/Roller/Working/Web/ponds_web/node_modules/express-session/index.js:257:22)
        at onsave (/Users/Roller/Working/Web/ponds_web/node_modules/express-session/index.js:325:11)
        at .<anonymous> (/Users/Roller/Working/Web/ponds_web/node_modules/express-sequelize-session/lib/e4store.js:88:51)
        at tryCatcher (/Users/Roller/Working/Web/ponds_web/node_modules/bluebird/js/release/util.js:16:23)
        at Promise._settlePromiseFromHandler (/Users/Roller/Working/Web/ponds_web/node_modules/bluebird/js/release/promise.js:504:31)
        at Promise._settlePromise (/Users/Roller/Working/Web/ponds_web/node_modules/bluebird/js/release/promise.js:561:18)
        at Promise._settlePromise0 (/Users/Roller/Working/Web/ponds_web/node_modules/bluebird/js/release/promise.js:606:10)
        at Promise._settlePromises (/Users/Roller/Working/Web/ponds_web/node_modules/bluebird/js/release/promise.js:685:18)
        at Async._drainQueue (/Users/Roller/Working/Web/ponds_web/node_modules/bluebird/js/release/async.js:138:16)
        at Async._drainQueues (/Users/Roller/Working/Web/ponds_web/node_modules/bluebird/js/release/async.js:148:10)
    Warning: Unexpected block "main"  on line 3 of /Users/Roller/Working/Web/ponds_web/app/views/500.jade. This block is never used. This warning will be an error in v2.0.0

这是我可以去的地方。在创建新产品后,我真的不想编写ProductAges控制器来手动将ProductId和AgeId添加到ProductAges模型中。由于已经有一个内置函数可以添加交集表数据。 Sequelize Belongs-To-Many associations我确信有一种更简单的方法。

请帮忙指导。谢谢。

1 个答案:

答案 0 :(得分:0)

您可以一次创建product及其相关的ages。见Creating elements of a "HasMany" or "BelongsToMany" association。首先尝试这种方法。