在sequelize,如果我有這樣的關聯:多外鍵Sequelize
User.hasMany(models.Article, { onDelete: 'cascade', hooks: true});
Sequelize會自動添加UserId
列Article
表。但現在我想添加更多像UserName
和Email
到Article
,所以當我查詢一篇文章我有作者的名字,我不需要再次查詢UserId。
我該怎麼做?我試圖
User.hasMany(models.Article, { onDelete: 'cascade', hooks: true, foreignKey: {'UserId': 'id', 'UserName': 'name' } });
但只UserId
出現在Article
表。
這裏是我的用戶模型:
"use strict";
var bcrypt = require('bcryptjs');
module.exports = function (sequelize, DataTypes) {
var User = sequelize.define('User', {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
name: {
type: DataTypes.STRING,
primaryKey: true
},
password: {
type: DataTypes.STRING,
allowNull: false
},
email: {
type: DataTypes.STRING,
primaryKey: true
},
role: {
type: DataTypes.STRING,
allowNull: false
},
activeToken: {
type: DataTypes.STRING,
allowNull: false,
},
status: {
type: DataTypes.BOOLEAN,
defaultValue: false,
allowNull: false
},
avatar: {
type: DataTypes.STRING,
allowNull: true
},
phone: {
type: DataTypes.STRING,
allowNull: true
}
}, {
instanceMethods: {
updatePassword: function (newPass, callback) {
var self = this;
bcrypt.genSalt(10, function (err, salt) {
bcrypt.hash(newPass, salt, function (err, hashed) {
self.update({
password: hashed
}).then(callback);
});
});
},
updateStatus: function (status, callback) {
this.update({
status: status
}).then(callback);
},
comparePassword: function (password, callback) {
bcrypt.compare(password, this.password, function (err, isMatch) {
if (err) {
throw err;
}
callback(isMatch);
});
},
updateRole: function (newRole, callback) {
this.update({
role: newRole
}).then(callback);
}
},
classMethods: {
createUser: function (newUser, callback) {
bcrypt.genSalt(10, function (err, salt) {
bcrypt.hash(newUser.password, salt, function (err, hash) {
newUser.password = hash;
User.create(newUser).then(callback);
});
});
},
getUserById: function (id, callback) {
var query = {
where: {
id: id
}
}
User.findOne(query).then(callback);
},
getUserByUsername: function (username, callback) {
var query = {
where: {
username: username
}
};
User.findOne(query).then(callback);
},
getUserByEmail: function (email, callback) {
var query = {
where: {
email: email
}
};
User.findOne(query).then(callback);
},
getAllUser: function (callback) {
User.findAll().then(callback);
},
deleteUser: function (userId, callback) {
var query = {
where: {
id: userId
}
};
User.destroy(query).then(callback);
},
associate: function (models) {
User.hasMany(models.Article, { onDelete: 'cascade', hooks: true, onUpdate: 'cascade', foreignKey: {'UserId': 'id', 'UserName': 'name' } });
User.hasMany(models.Comment, { onDelete: 'cascade', hooks: true, onUpdate: 'cascade' });
User.hasMany(models.Device, { onDelete: 'cascade', hooks: true, onUpdate: 'cascade' });
}
},
tableName: 'User'
});
return User;
};
這是行不通的。外鍵必須映射到一個'用戶',你可以有一個名字映射到許多用戶。您基本上想要將用戶表中的名稱和電子郵件複製到文章表中。這不是一個好習慣。 –