Sequelize无法将值添加到关联对象中

时间:2016-01-08 02:30:13

标签: express sequelize.js

我正在尝试使用子(关联)创建一个对象,该对象具有已创建对象的Id作为其属性的值传递。我试图遵循文档,但没有使用SQL命令传递任何值。

这是SQL查询:

INSERT INTO `organization` (`organization_id`,`organization_name`,`admin`,`updatedAt`,`createdAt`) VALUES (DEFAULT,'dfsadfadsfa','ter@test.cm','2016-01-08 02:23:04','2016-01-08 02:23:04');

不参考user

以下是插入组织的路线:

var express = require('express');
var appRoutes   = express.Router();
var passport = require('passport');
var localStrategy = require('passport-local').Strategy;
var models = require('../models/db-index');

    appRoutes.route('/sign-up/organization')

        .get(function(req, res){
            models.User.find({
                where: {
                    user_id: req.user.email
                }, attributes: [ 'user_id', 'email'
                ]
            }).then(function(user){
                res.render('pages/sign-up-organization.hbs',{
                    user: req.user
                });
            })

        })

        .post(function(req, res, user){
            models.Organization.create({
                organizationName: req.body.organizationName,
                admin: req.body.admin,
                User: [{
                    organizationId: req.body.organizationId
                }]
            }, { include: [models.User] }).then(function(){
                console.log(user.user_id);
                res.redirect('/app');
            }).catch(function(error){
                res.send(error);
                console.log('Error at Post');
            })
        });

以下是表单提交:

<div class="container">
        <div class="col-md-6 col-md-offset-3">
            <form action="/app/sign-up/organization" method="post">
                <p>{{user.email}}</p>
                <input type="hidden" name="admin" value="{{user.email}}">
                <input type="hidden" name="organizationId">
                <label for="sign-up-organization">Company/Organization Name</label>
                <input type="text" class="form-control" id="sign-up-organization"  name="organizationName" value="" placeholder="Company/Organization">
                <br />
                    <button type="submit">Submit</button>
            </form>

user.js型号:

var bcrypt   = require('bcrypt-nodejs');

module.exports = function(sequelize, DataTypes) {

var User = sequelize.define('user', {
    user_id: {
        type: DataTypes.INTEGER,
        autoIncrement: true,
        primaryKey: true
    },
    firstName: {
        type: DataTypes.STRING,
        field: 'first_name'
    },
    lastName: {
        type: DataTypes.STRING,
        field: 'last_name'
    },
    email: {
        type: DataTypes.STRING,
        isEmail: true,
        unique: true
    },
    password: DataTypes.STRING,
    organizationId: {
        type: DataTypes.INTEGER,
        field: 'organization_id',
        allowNull: true
    }
}, {
    freezeTableName: true,
    classMethods: {
        generateHash: function(password) {
            return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
        },
    },
    instanceMethods: {
        validPassword: function(password) {
            return bcrypt.compareSync(password, this.password);
        },
    },


});
    return User;
}

organization.js模型:

module.exports = function(sequelize, DataTypes) {

var Organization = sequelize.define('organization', {
    organizationId: {
        type: DataTypes.INTEGER,
        field: 'organization_id',
        autoIncrement: true,
        primaryKey: true
    },
    organizationName: {
        type: DataTypes.STRING,
        field: 'organization_name'
    },
    admin: DataTypes.STRING,
    members: DataTypes.STRING
},{
    freezeTableName: true,
    classMethods: {
        associate: function(db) {
            Organization.hasMany(db.User, {foreignKey: 'user_id'});
        },
    },
});

    return Organization;
}

db-index.js:两者相关联的地方:

var Sequelize = require('sequelize');
var path = require('path');
var config = require(path.resolve(__dirname, '..', '..','./config/config.js'));
var sequelize = new Sequelize(config.database, config.username, config.password, {
    host:'localhost',
    port:'3306',
    dialect: 'mysql'
});

sequelize.authenticate().then(function(err) {
    if (!!err) {
        console.log('Unable to connect to the database:', err)
    } else {
        console.log('Connection has been established successfully.')
    }
});

var db = {}

db.Organization = sequelize.import(__dirname + "/organization");

db.User = sequelize.import(__dirname + "/user");

db.Annotation = sequelize.import(__dirname + "/annotation");

db.Organization.associate(db);
db.Annotation.associate(db);

db.sequelize = sequelize;
db.Sequelize = Sequelize;

sequelize.sync();

module.exports = db;

1 个答案:

答案 0 :(得分:0)

当我使用Sequelize时,我通常会创建一个使用构建方法创建续集模型实例的函数,并使用该实例将该实例保存到数据库中。使用返回的实例,您可以执行任何操作。

var instance = models.Organization.build(data);
instance.save().then(function(savedOrgInstance){
    savedOrgInstance.createUser(userData).then(function(responseData){
    //do whatever you want with the callback })
})

我不能说我已经看过你写过的创建声明了。什么是额外的包含声明?

这应该为新创建的用户提供您正在寻找的关联。 您应该在文档中签出setAssociaton,getAssociation,createAssociation方法。 http://docs.sequelizejs.com/en/latest/docs/associations/