简体   繁体   English

(添加SQL)将hasMany与选项关联

[英](Added SQL) Sequelize hasMany association with option

I'm new to Sequelize and I'm learning with the official tutorial site( http://docs.sequelizejs.com/manual/tutorial/ ) I got stuck while trying the code on the tutorial. 我是Sequelize的新手,正在学习官方教程网站( http://docs.sequelizejs.com/manual/tutorial/ ),但在尝试教程中的代码时遇到了麻烦。

The code I tried was this: 我尝试的代码是这样的:

 const City = sequelize.define('city', { countryCode: Sequelize.STRING }); const Country = sequelize.define('country', { isoCode: Sequelize.STRING }); Country.hasMany(City, {foreignKey: 'countryCode', sourceKey: 'isoCode'}); City.belongsTo(Country, {foreignKey: 'countryCode', targetKey: 'isoCode'}); sequelize.sync(); 

When I run this code, node console gives me back an error: 当我运行此代码时,节点控制台会给我一个错误:

"Unhandled rejection SequelizeDatabaseError: Failed to add the foreign key constraint. Missing index for constraint 'cities_ibfk_1' in the referenced table 'countries'" “未处理的拒绝SequelizeDatabaseError:无法添加外键约束。在引用表'countries'中缺少约束'cities_ibfk_1'的索引”

Could anybody give me what is wrong with this? 有人可以告诉我这是什么问题吗? I really appreciate your help. 非常感谢您的帮助。 Thank you. 谢谢。

The code above is from Assotiation part of the tutorial ( http://docs.sequelizejs.com/manual/tutorial/associations.html ) One-to Many associations. 上面的代码是从教程(的一部分Assotiation http://docs.sequelizejs.com/manual/tutorial/associations.html )一对多关联。


I also attach the code auto-generated by Sequelize: 我还附上了Sequelize自动生成的代码:

CREATE TABLE IF NOT EXISTS `countries` (
  `id` INTEGER NOT NULL auto_increment ,
  `isoCode` VARCHAR(255),
  `createdAt` DATETIME NOT NULL,
  `updatedAt` DATETIME NOT NULL,
  PRIMARY KEY (`id`))
  ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS `cities` (
  `id` INTEGER NOT NULL auto_increment ,
  `createdAt` DATETIME NOT NULL,
  `updatedAt` DATETIME NOT NULL,
  `countryCode` VARCHAR(255),
  PRIMARY KEY (`id`),
  FOREIGN KEY (`countryCode`) REFERENCES `countries` (`isoCode`)
  ON DELETE SET NULL ON UPDATE CASCADE)
  ENGINE=InnoDB;

In glance it doesn't seem SQL syntax is wrong here, but anyhow this makes the error. 乍一看,似乎SQL语法在这里不是错误的,但是无论如何都会导致错误。 Can anyone figure out what is wrong? 任何人都可以找出问题所在吗? Or is this a problem of Sequelize? 还是这是续集的问题?

This error occurred because the example code in Sequelize tutorial has an syntax error. 发生此错误的原因是Sequelize教程中的示例代码存在语法错误。

If we want to make rule for a foreign key, it has to reference the primary key of the referenced table. 如果要为外键制定规则,则它必须引用被引用表的主键。 The problem is that in the code, the foreign key countryCode is trying to reference the isoCode of Country model(which is countries table in real MySQL DB). 问题是,在代码中,外键countryCode试图引用isoCodeCountry模型(这是countries表中实际MySQL数据库)。

const City = sequelize.define('city', { countryCode: Sequelize.STRING });
const Country = sequelize.define('country', { isoCode: Sequelize.STRING });

Country.hasMany(City, {foreignKey: 'countryCode', sourceKey: 'isoCode'});
City.belongsTo(Country, {foreignKey: 'countryCode', targetKey: 'isoCode'});

The Sequelize code above will be converted into SQL statement like this below: 上面的Sequelize代码将转换为如下的SQL语句:

CREATE TABLE IF NOT EXISTS `countries` (
  `id` INTEGER NOT NULL auto_increment ,
  `isoCode` VARCHAR(255),
  `createdAt` DATETIME NOT NULL,
  `updatedAt` DATETIME NOT NULL,
  PRIMARY KEY (`id`))
  ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS `cities` (
  `id` INTEGER NOT NULL auto_increment ,
  `createdAt` DATETIME NOT NULL,
  `updatedAt` DATETIME NOT NULL,
  `countryCode` VARCHAR(255),
  PRIMARY KEY (`id`),
  FOREIGN KEY (`countryCode`) REFERENCES `countries` (`isoCode`)
  ON DELETE SET NULL ON UPDATE CASCADE)
  ENGINE=InnoDB;

To make this syntax error fixed, we have to make isoCode of City model a primary key. 为了使这个语法错误固定的,我们必须做出isoCodeCity模型中的主键。 Let's fix the code: 让我们修复代码:

const City = sequelize.define('city', { countryCode: Sequelize.STRING})
const Country = sequelize.define('country', {
  isoCode: {
    type: Sequelize.STRING,
    primaryKey: true
  }
})
// ... the rest of code followed below

As we fixed the model definition, the code will be working fine as we expected! 固定模型定义后,代码将按预期工作!

But what I wonder is... how could the official tutorial post this code and let the beginners just try out it without knowing that this would not work. 但是我想知道的是... 官方教程如何发布此代码,让初学者只是在不知道这行不通的情况下尝试一下。 Of course, someone would say this is not a problem of Sequelize, but rather the problem of understanding SQL. 当然,有人会说这不是Sequelize的问题,而是理解SQL的问题。 But still I think the tutorial should be fixed to avoid this kind of happening. 但是我仍然认为该教程应该固定以避免这种情况的发生。


The limitation of this solution is that, there is no point of using the option sourceKey and targetKey , because even without them, Sequelize will automatically figure out the relationship and recognize what is the source key and target key among the tables. 该解决方案的局限性在于,没有必要使用选项sourceKeytargetKey ,因为即使没有它们,Sequelize也会自动找出关系并识别表中的源键和目标键。

Still I don't get the point... I think for now, I just have to not use the sourceKey and targetkey options. 仍然我不明白这一点……我想现在,我只需要不使用sourceKey和targetkey选项。

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

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