简体   繁体   English

无法在Sequelize中联接表

[英]Cannot join tables in Sequelize

I have 2 simple tables in a sqlite file: assets: {id, symbol, name} - all text fields ratings: {symbol, rating} - all text fields 我在sqlite文件中有2个简单表:资产:{id,symbol,name}-所有文本字段评分:{symbol,rating}-所有文本字段

I'm trying to get a query that will get {id, symbol, name, rating}, but I must be missing something, because rating always comes back as null . 我正在尝试获取一个{id,符号,名称,等级}的查询,但是我必须缺少一些东西,因为等级总是返回null

Things I tried: 我尝试过的事情:

  1. Adding 2 associations ( hasOne and belongsTo ) 添加2个关联( hasOnebelongsTo
  2. Adding references to the foreign key in the ratings model 在评级模型中添加对外键的references
  3. Adding targetKey field name to the association targetKey字段名称添加到关联中

Here's my code: schemas, models, association, and query: 这是我的代码:模式,模型,关联和查询:

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;
    }
  }

Can someone please point out what I'm missing? 有人可以指出我所缺少的吗?

Update: 更新:
per request, turned on logging, got the following SQL: 每个请求打开日志记录,都会得到以下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';

The result: 结果:

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

A row with symbol = 'xyz' exists in both tables. 两个表中都存在带有symbol = 'xyz'行。

I think the issue is with association , 我认为问题在于关联,

Add this line also : 也添加此行:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM