gpt4 book ai didi

node.js - Sequelize finder 排除了属性但想要所有属性

转载 作者:行者123 更新时间:2023-12-03 22:33:29 25 4
gpt4 key购买 nike

我将 sequelize 与 nodeJs 一起使用。
我有一个带有外键的表,但我不知道为什么,它们没有出现在查询中。

import { Model, DataTypes } from "sequelize"
import { sequelize } from "./config"

class VolumeRangeDiscount extends Model{
public readonly id: number;
public readonly updatedAt!:Date;
public readonly createdAt!:Date;
public discount: number;

public static associate(models){
VolumeRangeDiscount.belongsTo(models.VolumeRange, {
foreignKey: "volumeRangeId",
as: "volumeRange",
});
VolumeRangeDiscount.belongsTo(models.Pack, {
foreignKey: "packId",
as: "pack",
});
}
}

VolumeRangeDiscount.init({
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER,
},
createdAt: {
type: DataTypes.DATE,
allowNull: false,
},
updatedAt: {
type: DataTypes.DATE,
allowNull: false,
},
discount:{
type: DataTypes.INTEGER,
allowNull: true,
}

}, { sequelize, tableName: "VolumeRangeDiscount" })



export default VolumeRangeDiscount
当我想通过 id 查找时,它不会查询外键列:
export function findVolumeRangeDiscountById(id) {
return VolumeRangeDiscount.findOne({ where: { id }, raw: true });
}
生成的查询是:
SELECT "id", "createdAt", "updatedAt", "discount" FROM "VolumeRangeDiscount" AS "VolumeRangeDiscount" WHERE "VolumeRangeDiscount"."id" = '3';
但是如果我添加属性选项和它工作的列名,它们会被返回。
您知道为什么默认情况下它们不在生成的查询中吗?
它不会在我的模型中添加外键,VolumeRangeDiscount.rawAttributes 返回:
 {
id: {allowNull: false,
autoIncrement: true,
primaryKey: true,
type: INTEGER {
options: {
},
_length: undefined,
_zerofill: undefined,
_decimals: undefined,
_precision: undefined,
_scale: undefined,
_unsigned: undefined},
Model: VolumeRangeDiscount,
fieldName: 'id',
_modelAttribute: true,
field: 'id'
},
createdAt: {type: DATE {options: [Object], _length: ''
},
allowNull: false,
Model: VolumeRangeDiscount,
fieldName: 'createdAt',
_modelAttribute: true,
field: 'createdAt'},
updatedAt: { type: DATE {options: [Object], _length: ''
},
allowNull: false,
Model: VolumeRangeDiscount,
fieldName: 'updatedAt',
_modelAttribute: true,
field: 'updatedAt'},
discount: {type: INTEGER {
options: {},
_length: undefined,
_zerofill: undefined,
_decimals: undefined,
_precision: undefined,
_scale: undefined,
_unsigned: undefined
},
allowNull: true,
Model: VolumeRangeDiscount,
fieldName: 'discount',
_modelAttribute: true,
field: 'discount'},
}

最佳答案

Sequelize 是一个 ORM,它为您处理关联。您可以使用它以两种方式获取关联行,而不是获取外键:

  • 急切加载
    VolumeRangeDiscount.findOne({ where: { id }, include 'VolumeRange' });
    这将使用关联的行填充 VolumeRange 对象。
  • 懒加载
     const vrDiscount = VolumeRangeDiscount.findOne({ where: { id }, include 'VolumeRange' });
    const volumeRange = vrDiscount.getVolumeRange();

  • 可以在 docs here 中找到更多关于此的信息。

    关于node.js - Sequelize finder 排除了属性但想要所有属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64461211/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com