我有两个模特, User
以及 Category
用户模型:
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
id: {
type: DataTypes.BIGINT(19),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
firstname: {
type: DataTypes.STRING(150),
allowNull: false
},
lastname: {
type: DataTypes.STRING(150),
allowNull: false
},
email: {
type: DataTypes.STRING(255),
allowNull: false,
unique: true
},
password: {
type: DataTypes.STRING(255),
allowNull: false
}
}, {
tableName: 'users',
timestamps: true,
createdAt: 'created_at',
updatedAt: 'updated_at',
defaultScope: {
attributes: {
exclude: ['password']
}
},
scopes: {
withPassword: {
attributes: {}
}
}
})
User.prototype.toJSON = function () {
let values = Object.assign({}, this.get())
delete values.password
return values
}
return User
}
类别模型:
module.exports = (sequelize, DataTypes) => {
const Category = sequelize.define('Category', {
id: {
type: DataTypes.BIGINT(19),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
name: {
type: DataTypes.STRING(150),
allowNull: false
},
created_by: {
type: DataTypes.BIGINT(19),
allowNull: false,
references: {
model: 'users',
key: 'id'
}
}
}, {
tableName: 'categories',
timestamps: true,
createdAt: 'created_at',
updatedAt: 'updated_at'
})
Category.associate = (models) => {
Category.belongsTo(models.User, {
foreignKey: 'created_by'
})
}
return Category
}
查找类别的查询:
const category = await Category.findOne({
include: [{
model: User,
required: true,
attributes: ['id', 'firstname', 'lastname', 'email']
}],
where: {
id: req.params.id
},
limit: 1
})
当我执行查询时,我预期的响应是,
{
"id": 1,
"name": "License",
"created_by": {
"id": 1,
"firstname": "Magesh",
"lastname": "Kumaar",
"email": "mk@test.com"
},
"created_at": "2018-09-03T07:41:29.000Z",
"updated_at": "2018-09-03T07:41:29.000Z"
}
但我得到的答复是,
{
"id": 1,
"name": "License",
"created_by": 1, // I expected the user information here
"created_at": "2018-09-03T07:41:29.000Z",
"updated_at": "2018-09-03T07:41:29.000Z",
"User": {
"id": 1,
"firstname": "Magesh",
"lastname": "Kumaar",
"email": "mk@test.com"
}
}
用户信息在这两个位置都可用 created_by
作为身份证和其他 User
包含其他信息的属性
我试过了 as
但它似乎不起作用。有没有什么方法可以在 created_by
密钥本身。
1条答案
按热度按时间huwehgph1#
需要使用别名。http://docs.sequelizejs.com/manual/tutorial/associations.html
例子:
索引.js
类别模型文件:
结果: