Sequelize:原始数据和模型之间的映射

编程入门 行业动态 更新时间:2024-10-27 19:15:13
本文介绍了Sequelize:原始数据和模型之间的映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在使用原始查询从 MySQL 数据库中检索数据时遇到了一些麻烦.问题在于原始数据和 sequelize 中定义的模型实例之间的映射.特别是那些在数据库中带有下划线名称并在模型中使用驼峰格式的字段.

I have some trouble to retrieve data from MySQL database using a raw query. The problem is the mapping between raw data and the instances of model defined in sequelize. In particular those fields that have underscored names in the database and camelcased in the model.

我以这种方式定义了 Store 模型:

I defined the Store model in this way:

sequelize.define('stores', { id: { type: DataTypes.INTEGER(11), allowNull: false, primaryKey: true, autoIncrement: true }, ... postalCode: { type: DataTypes.STRING, field: 'postal_code', }, ... }

我使用以下代码从数据库中的例程中获取数据:

and I get data from a routine in the database using this code:

sequelize.query('CALL get_stores()', {model: Stores, type: sequelize.QueryTypes.RAW}).then(function (stores) { console.log(stores); }

根据文档(docs.sequelizejs/en/latest/docs/raw-queries/) 如果我定义了模型"选项,该函数将返回 Store 的一个实例而不是原始数据.但这不是真的,对于模型和数据库中名称不同的所有字段(请参阅 postalCode -> postal_code),我得到的响应返回一个带有数据库字段名称(postal_code)的对象,而不是在模型(邮政编码).

according to the documentation (docs.sequelizejs/en/latest/docs/raw-queries/) if I define the option "model" the function returns an instance of Store instead of raw data. But this is not true and, for all fields whose name is different in the model and in the database (see postalCode -> postal_code), the response I get returns an object with the database field names (postal_code) instead of those defined in the model (postalCode).

我已经尝试使用 QueryTypes.SELECT 而不是 QueryTypes.RAW 但没有成功.

I already tried using QueryTypes.SELECT instead of QueryTypes.RAW but without success.

请注意,使用 findAll 或 findOne 方法时没有问题.

Please note that there is no problem when using the findAll or findOne method.

推荐答案

您可以在查询中设置选项 mapToModel: true 以指示 Sequelize 将返回的字段名称转换为模型中的等效项您提供.

You can set the option mapToModel: true in your query to instruct Sequelize to translate the returned field names to the equivalent in the model you provide.

const User = sequelize.define('user', { userId: { field: 'user_id', type: DataTypes.BIGINT, primaryKey: true }) sequelize.query( 'select user_id from user where user_id > 1000', { mapToModel: true, model: User } )

此功能隐藏在参考文档中:docs.sequelizejs/class/lib/sequelize.js~Sequelize.html#instance-method-query

This feature is tucked away in the reference documentation: docs.sequelizejs/class/lib/sequelize.js~Sequelize.html#instance-method-query

更多推荐

Sequelize:原始数据和模型之间的映射

本文发布于:2023-10-31 08:03:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545513.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模型   原始数据   Sequelize

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!