问题是我无法使用关系 hasOne,它不会急切加载状态类型对象。
所有查询都在现有表上完成。
这是客户表,重要的是cst_state_type
字段:
module.exports = function(sequelize, DataTypes) {
return sequelize.define('customer', {
customer: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: true,
validate: {
isNumeric: true
}
},
first_name: {
type: DataTypes.STRING(100),
validate: {
isAlphanumeric: true
}
},
last_name: DataTypes.STRING(100),
identity_code: {
type: DataTypes.STRING(20),
allowNull: true,
validate: {
isNumeric: true
}
},
note: DataTypes.STRING(1000),
birth_date: DataTypes.DATE,
created_by: DataTypes.INTEGER,
updated_by: DataTypes.INTEGER,
cst_type: DataTypes.INTEGER,
cst_state_type: {
type: DataTypes.INTEGER,
}
}, {
tableName: 'customer',
updatedAt: 'updated',
createdAt: 'created',
timestamps: true
});
};
cst_state_type 表:
module.exports = function(sequelize, DataTypes) {
return sequelize.define('StateType', {
cst_state_type: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
validate: {
}
},
name: DataTypes.STRING(100),
}, {
tableName: 'cst_state_type',
timestamps: false
});
};
如何描述关系:
global.db.Customer.hasOne(global.db.StateType, {
foreignKey: 'cst_state_type',
as: 'state_type'
});
global.db.StateType.belongsTo(global.db.Customer, {
foreignKey: 'cst_state_type'
});
并创建急切加载查询:
db.Customer.findAll( {
include: [
{ model: db.Address, as: 'addresses' },
{ model: db.StateType, as: 'state_type' }
]
})
.success(function (customers) {
res.json(200, customers);
})
.fail(function (error) {
res.json(500, { msg: error });
});