模型定义
const DataTypes = Sequelize.DataTypes;
const user = sequelize.define('u', {
userId: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
userName: {
type: DataTypes.STRING,
allowNull: true
},
birthDay: {
type: 'TIMESTAMP',
allowNull: false
},
gender: {
type: DataTypes.INTEGER,
allowNull: true,
defaultValue: 0
},
ctime: {
type: 'TIMESTAMP',
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP')
},
updatedAt: {
type: 'TIMESTAMP',
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
field: 'ctime'
}
}, {
tableName: 'user'
})
const products = sequelize.define('p', {
prdId: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
prdName: {
type: DataTypes.STRING,
allowNull: false
},
userId: {
type: DataTypes.INTEGER,
allowNull: false
},
price: {
type: DataTypes.DECIMAL(5, 4),
allowNull: false
}
})
products.belongsTo(user, { foreignKey: 'userId', targetKey: 'userId', as: 'u' });
注意点:
1. type 如果不存在则直接用字符串表示 如:’TIMESTAMP’;
2. 如果需要在更新表字段时记录更新时间,可应使用 updateAt,并设置默认值和对应的字段名。
3. 如果默认值不是具体的数值,可以用 literal 函数去表示。
4. tableName 表名,u 为别名。
5. 建立关联关系时,如果外键关联的是主键则不用写 targetKey,否则需要。
查询
方式一
products.findAll({
attributes: ['prdName', 'price'],
include: [{
model: user,
as: 'u',
attributes: ['userName']
}],
//raw:true
}).then(result => {
console.log(JSON.stringify(result))
}).catch(err => {
console.log(err)
});
结果:
[
{
"prdName": "ipad",
"price": 4.99,
"u": { "userName": "张三" }
},
{
"prdName": "iphone",
"price": 3.658,
"u": { "userName": "张三" }
},
{
"prdName": "联想笔记本",
"price": 9.32,
"u": { "userName": "李四" }
}
]
方式二
products.findAll({
attributes: ['prdName', 'price'],
include: [{
model: user,
as: 'u',
attributes: ['userName']
}],
raw:true
}).then(result => {
console.log(JSON.stringify(result))
}).catch(err => {
console.log(err)
});
结果:
[
{
"prdName":"ipad",
"price":4.99,
"u.userName":"张三"
},
{
"prdName":"iphone",
"price":3.658,
"u.userName":"张三"
},
{
"prdName":"联想笔记本",
"price":9.32,
"u.userName":"李四"
}
]
方式三
products.findAll({
attributes: [Sequelize.col('u.userName'),'prdName', 'price'],
include: [{
model: user,
as: 'u',
attributes: []
}],
raw:true
}).then(result => {
console.log(JSON.stringify(result))
}).catch(err => {
console.log(err)
});
结果:
[
{
"userName":"张三",
"prdName":"ipad",
"price":4.99
},
{
"userName":"张三",
"prdName":"iphone",
"price":3.658
},
{
"userName":"李四",
"prdName":"联想笔记本",
"price":9.32
}
]
方式三成功把关联表的字段合并到了当前表数据里面。棒棒哒。
本文来自 connection people 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/weixin_37778679/article/details/82692584