Express Sequelize Can';t向关联对象添加值
我试图创建一个具有子对象(关联)的对象,该子对象的Id作为值传递给其属性。我已经尝试按照文档进行操作,但是SQL命令没有传递任何值 以下是SQL查询:Express Sequelize Can';t向关联对象添加值,express,sequelize.js,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-
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');
未提及用户
以下是插入组织的路径:
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>
organization.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;
}
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;
当我使用Sequelize时,我通常创建一个函数,使用build方法创建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 })
})
我不能说我看到过你写的create语句。额外的include声明用于什么
这将为新创建的用户提供您正在寻找的关联。
您应该签出文档中的setAssociation、getAssociation和createAssociation方法 如我所见,您是否尝试过表单提交?它不是/app,因为它称为路由文件。嘿,对不起,我在该文件中为正在调用的所有路由添加了/app。这不是一个问题Hey Cameron,我指的是文档中的这一部分,在路线的这一点上,我已经创建了一个经过授权的用户,这就是为什么我能够访问用户模型属性,但由于某些原因,我当前的创建方法找不到要传递给用户属性的组织id值。这是我的假设哈哈,我以前没用过那种方法,我不这么认为。不过,这些文档很有帮助。尝试执行用户:[{…:…}]而不是用户。复数可能是导致错误的原因。要使该方法起作用,您可能还需要用户模型中的User.belongsTo(models.Organization…)?只有两个想法!如果您的用户已经创建,那么包含已创建用户的create语句可能无法工作?看起来它会新建两个实例。就像我提到的,你可能会创建一个组织,如果你有用户ID,你可能只需要调用newOrgInstance.setUser(userData或instance)。我想这就是我所得到的不幸!似乎您必须同时创建实例,或者等到创建组织实例,然后将该值应用于用户模型,这是对的。I console.logged在语句中,它返回为undefined for
annotation
这是一个很好的迹象表明这不能一起工作吗?