gpt4 book ai didi

javascript - 无法在 Sequelize 中加入表

转载 作者:行者123 更新时间:2023-12-03 22:40:31 26 4
gpt4 key购买 nike

我在一个 sqlite 文件中有 2 个简单的表:
Assets :{id,符号,名称} - 所有文本字段
ratings: {symbol, rating} - 所有文本字段

我正在尝试获得一个将获得 {id, symbol, name, rating} 的查询,但我一定遗漏了一些东西,因为 rating 总是作为 null 返回。

我尝试过的事情:

  • 添加 2 个关联( hasOnebelongsTo )
  • references 添加到评分模型中的外键
  • targetKey 字段名称添加到关联

  • 这是我的代码:模式、模型、关联和查询:
    import Sequelize from 'sequelize';

    const sequelize = new Sequelize('sqlite:./stocks.sqlite3', {
    operatorsAliases: false,
    logging: false
    });

    const stocksSchema = {
    id: {type: Sequelize.STRING, primaryKey: true, allowNull: false},
    name: {type: Sequelize.STRING, allowNull: false},
    symbol: {type: Sequelize.STRING, allowNull: false}
    };

    const stocksModel = sequelize.define('stock', stocksSchema, {
    tableName: 'stocks',
    timestamps: false
    });

    const ratingsSchema = {
    symbol: {type: Sequelize.STRING, primaryKey: true, allowNull: false, references: {model: stocksModel, key: 'symbol'}},
    rating: {type: Sequelize.STRING(2), allowNull: false}
    };

    const ratingsModel = sequelize.define('rating', ratingsSchema, {
    tableName: 'ratings',
    timestamps: false
    });

    //association
    stocksModel.hasOne(ratingsModel, {foreignKey: 'symbol'});

    //query
    const getById = async (id) => {
    try {
    return await stocksModel.findOne({
    where: {id: id},
    include:[{model: ratingsModel}]})
    .then(result => result ? result.dataValues : Promise.reject('not found'));
    }
    catch(e) {
    console.error(e);
    throw e;
    }
    }

    有人可以指出我缺少什么吗?

    更新:
    每个请求,打开日志记录,得到以下 SQL:
    Executing (default): SELECT `stocks`.`id`, `stocks`.`name`, `stocks`.`symbol`, `rating`.`symbol` AS `rating.symbol`, `rating`.`rating` AS `rating.rating` FROM `stocks` AS `stocks` LEFT OUTER JOIN `ratings` AS `rating` ON `stocks`.`id` = `rating`.`symbol` WHERE `stocks`.`id` = 'XYZ';

    结果:
    dataValues: {
    id: 'XYZ',
    name: 'XYZStock',
    symbol: 'xyz',
    rating: null
    }

    两个表中都存在带有 symbol = 'xyz' 的行。

    最佳答案

    我认为问题出在关联上,

    也添加这一行:

    ratingsModel.belongsTo(stocksModel, {foreignKey: 'symbol' , targetKey : 'symbol' });

    关于javascript - 无法在 Sequelize 中加入表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48432838/

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