在开发 Web 应用时,利用 ORM 框架可以方便地对数据库进行操作,提高开发效率。Sequelize 是一款流行的 Node.js ORM 框架,它不仅支持多种关系型数据库,还提供了丰富的功能,如虚拟关联和计算字段。
虚拟关联
在 Sequelize 中,虚拟关联可以帮助我们在数据表之间建立关联关系,但不需要修改数据库结构。虚拟关联有以下两种常见情况。
一对一虚拟关联
假设我们有两个数据表:User 和 Address,它们之间存在一对一的关联关系。为了展示每个用户的地址信息,可以在 User 模型中定义一个虚拟关联 address,下面是实现示例。
// www.javascriptcn.com code example
const Address = sequelize.define('address', {
street: Sequelize.STRING,
city: Sequelize.STRING,
state: Sequelize.STRING,
zip: Sequelize.STRING
});
const User = sequelize.define('user', {
name: Sequelize.STRING
});
User.belongsTo(Address); // User 拥有一个外键 addressId,指向 Address 的 id
User.hasOne(Address, { as: 'address', foreignKey: 'userId' }); // 定义用户的地址虚拟关联
User.findAll({
include: [{
model: Address,
as: 'address',
attributes: ['street', 'city', 'state', 'zip'] // 限制返回的地址信息字段
}]
});在上面的示例中,belongsTo 表示 User 模型拥有一个外键 addressId,指向 Address 的 id,而 hasOne 则定义了一个名为 address 的虚拟关联。在查询 User 时,我们可以通过 include 参数一起查询关联的地址信息,返回字段也可以通过 attributes 限制。
一对多虚拟关联
假设有两个数据表:Blog 和 Comment,它们之间存在一对多的关联关系。为了展示每篇博客的评论列表,可以在 Blog 模型中定义一个虚拟关联 comments,下面是实现示例。
// www.javascriptcn.com code example
const Blog = sequelize.define('blog', {
title: Sequelize.STRING
});
const Comment = sequelize.define('comment', {
content: Sequelize.STRING
});
Blog.hasMany(Comment); // Blog 拥有多个评论
Blog.hasMany(Comment, { as: 'comments', foreignKey: 'blogId' }); // 定义博客的评论虚拟关联
Blog.findAll({
include: [{
model: Comment,
as: 'comments',
attributes: ['content'] // 限制返回的评论信息字段
}]
});在上面的示例中,hasMany 表示 Blog 模型拥有多个评论,而 hasMany 定义了一个名为 comments 的虚拟关联。在查询 Blog 时,我们可以通过 include 参数一起查询关联的评论列表,返回字段也可以通过 attributes 限制。
计算字段
在 Sequelize 中,计算字段可以帮助我们在查询数据库时直接计算出一些字段的值。计算字段有以下两种常见情况。
虚拟字段
假设有一个数据表 User,其中有 firstName 和 lastName 两个字段,现在我们想要查询时直接返回 fullName 字段,包括其拼接结果。可以定义一个虚拟字段 fullName,下面是实现示例。
// www.javascriptcn.com code example
const User = sequelize.define('user', {
firstName: Sequelize.STRING,
lastName: Sequelize.STRING,
fullName: {
type: Sequelize.VIRTUAL,
get() {
return `${this.firstName} ${this.lastName}`;
}
}
});
User.findAll({
attributes: ['fullName']
});在上面的示例中,虚拟字段 fullName 的类型为 VIRTUAL,其 get 函数将 firstName 和 lastName 进行拼接返回。在查询 User 时,我们可以通过 attributes 参数直接返回 fullName 字段。
聚合字段
假设有一个数据表 Order,其中有 price 和 quantity 两个字段,现在我们想要查询时直接返回 total 字段,包括其计算结果。可以定义一个聚合字段 total,下面是实现示例。
// www.javascriptcn.com code example
const Order = sequelize.define('order', {
price: Sequelize.DECIMAL,
quantity: Sequelize.INTEGER,
total: {
type: Sequelize.VIRTUAL,
get() {
return this.getDataValue('price') * this.getDataValue('quantity');
}
}
});
Order.findAll({
attributes: ['total']
});在上面的示例中,聚合字段 total 的类型为 VIRTUAL,其 get 函数将 price 和 quantity 相乘得到结果返回。在查询 Order 时,我们可以通过 attributes 参数直接返回 total 字段。
小结
通过本篇文章,我们学习了 Sequelize 的两种虚拟关联和两种计算字段的实现方式。虚拟关联可以帮助我们建立数据表之间的关联关系而不需要修改数据库结构,计算字段可以帮助我们在查询数据库时直接计算出一些字段的值,两者都有很重要的实际意义。
Source: FunTeaLearn,Please indicate the source for reprints https://funteas.com/post/67c0161c314edc268462c648