【发布时间】:2019-01-03 10:50:39
【问题描述】:
class User extends Sequelize.Model {
static init(sequelize, DataTypes) {
return super.init(
{
id: {type: DataTypes.INTEGER(11), allowNull: false, autoIncrement: true, primaryKey: true},
cityId: {
type: DataTypes.INTEGER(11).UNSIGNED,
field: 'city_id',
references: {
model: City,
key: 'city_id'
},
allowNull: false, defaultValue: 0
}
},
{
tableName: "users",
timestamps: false,
sequelize
}
);
}
static getByIdWithCity(id) {
return this.findOne({
where: {
id: {
[Op.eq]: id
}
},
include: [{model: City}],
raw: false
});
}
}
class City extends Sequelize.Model {
static init(sequelize, DataTypes) {
return super.init(
{
cityId: {type: DataTypes.INTEGER(11).UNSIGNED, allowNull: false, autoIncrement: true, primaryKey: true, field: 'city_id'},
countryId: {type: DataTypes.INTEGER(11).UNSIGNED, allowNull: false, default: 0, field: 'country_id'}
},
{
tableName: "city",
timestamps: false,
sequelize
}
);
}
}
User.belongsTo(City, {foreignKey: 'cityId', targetKey: 'cityId'});
City.hasOne(User, {foreignKey: 'cityId', sourceKey: 'cityId'});
getByIdWithCity 返回:
{
"id": 15,
"cityId": 3538,
"City": {
"cityId": 3538,
"countryId": 4
}
}
为什么返回cityId?
当然我可以排除这些字段:
static getByIdWithCity(id) {
return this.findOne({
where: {
id: {
[Op.eq]: id
}
},
attributes: { exclude: ['cityId'] },
include: [{
model: City,
}],
raw: false
});
}
但这是正确的方法吗?
【问题讨论】:
标签: node.js sequelize.js