(Added SQL) Sequelize hasMany association with option
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}
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.
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'"
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.
I also attach the code auto-generated by 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. Can anyone figure out what is wrong? Or is this a problem of Sequelize?
javascript mysql sql database sequelize.js
add a comment |
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.
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'"
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.
I also attach the code auto-generated by 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. Can anyone figure out what is wrong? Or is this a problem of Sequelize?
javascript mysql sql database sequelize.js
add a comment |
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.
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'"
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.
I also attach the code auto-generated by 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. Can anyone figure out what is wrong? Or is this a problem of Sequelize?
javascript mysql sql database sequelize.js
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.
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'"
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.
I also attach the code auto-generated by 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. Can anyone figure out what is wrong? Or is this a problem of Sequelize?
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();
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();
javascript mysql sql database sequelize.js
javascript mysql sql database sequelize.js
edited Jan 4 at 0:20
cadenzah
asked Jan 3 at 22:40
cadenzahcadenzah
597
597
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
This error occurred because the example code in Sequelize tutorial has an syntax error.
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).
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:
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. 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. 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.
Still I don't get the point... I think for now, I just have to not use the sourceKey and targetkey options.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54030802%2fadded-sql-sequelize-hasmany-association-with-option%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
This error occurred because the example code in Sequelize tutorial has an syntax error.
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).
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:
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. 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. 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.
Still I don't get the point... I think for now, I just have to not use the sourceKey and targetkey options.
add a comment |
This error occurred because the example code in Sequelize tutorial has an syntax error.
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).
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:
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. 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. 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.
Still I don't get the point... I think for now, I just have to not use the sourceKey and targetkey options.
add a comment |
This error occurred because the example code in Sequelize tutorial has an syntax error.
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).
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:
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. 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. 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.
Still I don't get the point... I think for now, I just have to not use the sourceKey and targetkey options.
This error occurred because the example code in Sequelize tutorial has an syntax error.
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).
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:
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. 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. 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.
Still I don't get the point... I think for now, I just have to not use the sourceKey and targetkey options.
edited Jan 4 at 1:29
answered Jan 4 at 1:11
cadenzahcadenzah
597
597
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54030802%2fadded-sql-sequelize-hasmany-association-with-option%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown