Problem with setting a value in foreign key columnHow can foreign key constraints be temporarily disabled using T-SQL?How do I see all foreign keys to a table or column?Cannot truncate table because it is being referenced by a FOREIGN KEY constraint?How to find all tables that have foreign keys that reference particular table.column and have values for those foreign keys?MySQL DROP all tables, ignoring foreign keysHow to truncate a foreign key constrained table?Add Foreign Key to existing tablewhy do i get this error in creating row in sequelize in node.js?unrecognized configuration parameter “autocommit” in PostgreSQL NodeJSWebpack Error: please install sqlite3 package manually
What word can be used to describe a bug in a movie?
Is TA-ing worth the opportunity cost?
I want to copy my HOME folder to a USB flash drive but I can't. I accidentally removed Python 3 and lost many important stuff
How to mark beverage cans in a cooler for a blind person?
Is refreshing multiple times a test case for web applications?
Improving software when the author can see no need for improvement
How to identify the wires on the dimmer to convert it to Conventional on/off switch
How to help new students accept function notation
Infeasibility in mathematical optimization models
Does a code snippet compile? Or does it gets compiled?
Can I call myself an assistant professor without a PhD
Colleagues speaking another language and it impacts work
Looking for a new job because of relocation - is it okay to tell the real reason?
Can a College of Swords bard use Blade Flourishes multiple times in a turn?
Does this Foo machine halt?
Can you use Shapechange with character feats to Grapple the Tarrasque?
Geometric programming: Why are the constraints defined to be less than/equal to 1?
How do we avoid CI-driven development...?
Why does this Pokémon I just hatched need to be healed?
Are there any financial disadvantages to living significantly "below your means"?
How would I as a DM create a smart phone-like spell/device my players could use?
Is there a way to create a report for the failed entries while calling REST API
Why should public servants be apolitical?
Non-OR journals which regularly publish OR research
Problem with setting a value in foreign key column
How can foreign key constraints be temporarily disabled using T-SQL?How do I see all foreign keys to a table or column?Cannot truncate table because it is being referenced by a FOREIGN KEY constraint?How to find all tables that have foreign keys that reference particular table.column and have values for those foreign keys?MySQL DROP all tables, ignoring foreign keysHow to truncate a foreign key constrained table?Add Foreign Key to existing tablewhy do i get this error in creating row in sequelize in node.js?unrecognized configuration parameter “autocommit” in PostgreSQL NodeJSWebpack Error: please install sqlite3 package manually
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
I'm using Sequelize.js with SQLite-database and faced a question with setting a value for foreign key. I have the following code:
const MessageModel = sequelize.define('MessageModel ',
uuid: DataTypes.STRING,
authorId: DataTypes.STRING,
// ... other props
, );
const TodoModel = sequelize.define('TodoModel',
ownerId: DataTypes.STRING,
status:
type: DataTypes.STRING,
defaultValue: 'pending'
, );
TodoModel.belongsTo(MessageModel ,
foreignKey:
name: 'messageId',
field: 'messageId',
allowNull: false
,
targetKey: 'uuid'
);
MessageModel.create(
uuid: 'testUUIDForExample'
// other props
).then(message =>
console.log(`Message's created successful`);
TodoModel.create(
ownerId: 'id-string',
status: 'test-status',
messageId: 'testUUIDForExample'
)
)
Sequelize creates MessageModel-row in DB, but it falls when it's trying to generate TodoModel with this err:
DatabaseError: SQLITE_ERROR: foreign key mismatch - "TodoModel" referencing "MessageModel "
at Query.formatError (C:Userslrsvoweb-developmentprojectsplatoon-web-electronnode_modulessequelizelibdialectssqlitequery.js:432:16)
at Query._handleQueryResponse (C:Userslrsvoweb-developmentprojectsplatoon-web-electronnode_modulessequelizelibdialectssqlitequery.js:77:18)
at afterExecute (C:Userslrsvoweb-developmentprojectsplatoon-web-electronnode_modulessequelizelibdialectssqlitequery.js:260:31)
at Statement.errBack (C:Userslrsvoweb-developmentprojectsplatoon-web-electronnode_modulessqlite3libsqlite3.js:16:21)
Err.original.message: "SQLITE_ERROR: foreign key mismatch - "TodoModel" referencing "MessageModel"
Generated SQL:
"INSERT INTO `TodoModel` (`id`,`ownerId`,`status`,`createdAt`,`updatedAt`,`messageId`) VALUES (NULL,$1,$2,$3,$4,$5);"
My TodoModel table looks like:
CREATE TABLE "TodoModel" (
"id" INTEGER PRIMARY KEY AUTOINCREMENT,
"ownerId" VARCHAR(255),
"status" TEXT DEFAULT 'pending',
"createdAt" DATETIME NOT NULL,
"updatedAt" DATETIME NOT NULL,
"messageId" VARCHAR(255) NOT NULL,
FOREIGN KEY("messageId") REFERENCES "MessageModel"("uuid") ON DELETE NO ACTION ON UPDATE CASCADE
);
I can't get why is the err occurs and need help, cause I'm dummy in this ORM.
I'm using "sequelize": "^5.1.0" with SQLite.
MyConfig file:
const Sequelize = require("sequelize");
const electron = require('electron');
const storagePath = electron.app.getPath('userData') + '/plt.db';
module.exports =
development:
dialect: "sqlite",
storage: storagePath,
username: null,
password: null,
operatorsAliases: Sequelize.Op,
define: freezeTableName: true ,
query: raw: true , // Always get raw result
logging: true,
,
;
foreign-keys sequelize.js
add a comment |
I'm using Sequelize.js with SQLite-database and faced a question with setting a value for foreign key. I have the following code:
const MessageModel = sequelize.define('MessageModel ',
uuid: DataTypes.STRING,
authorId: DataTypes.STRING,
// ... other props
, );
const TodoModel = sequelize.define('TodoModel',
ownerId: DataTypes.STRING,
status:
type: DataTypes.STRING,
defaultValue: 'pending'
, );
TodoModel.belongsTo(MessageModel ,
foreignKey:
name: 'messageId',
field: 'messageId',
allowNull: false
,
targetKey: 'uuid'
);
MessageModel.create(
uuid: 'testUUIDForExample'
// other props
).then(message =>
console.log(`Message's created successful`);
TodoModel.create(
ownerId: 'id-string',
status: 'test-status',
messageId: 'testUUIDForExample'
)
)
Sequelize creates MessageModel-row in DB, but it falls when it's trying to generate TodoModel with this err:
DatabaseError: SQLITE_ERROR: foreign key mismatch - "TodoModel" referencing "MessageModel "
at Query.formatError (C:Userslrsvoweb-developmentprojectsplatoon-web-electronnode_modulessequelizelibdialectssqlitequery.js:432:16)
at Query._handleQueryResponse (C:Userslrsvoweb-developmentprojectsplatoon-web-electronnode_modulessequelizelibdialectssqlitequery.js:77:18)
at afterExecute (C:Userslrsvoweb-developmentprojectsplatoon-web-electronnode_modulessequelizelibdialectssqlitequery.js:260:31)
at Statement.errBack (C:Userslrsvoweb-developmentprojectsplatoon-web-electronnode_modulessqlite3libsqlite3.js:16:21)
Err.original.message: "SQLITE_ERROR: foreign key mismatch - "TodoModel" referencing "MessageModel"
Generated SQL:
"INSERT INTO `TodoModel` (`id`,`ownerId`,`status`,`createdAt`,`updatedAt`,`messageId`) VALUES (NULL,$1,$2,$3,$4,$5);"
My TodoModel table looks like:
CREATE TABLE "TodoModel" (
"id" INTEGER PRIMARY KEY AUTOINCREMENT,
"ownerId" VARCHAR(255),
"status" TEXT DEFAULT 'pending',
"createdAt" DATETIME NOT NULL,
"updatedAt" DATETIME NOT NULL,
"messageId" VARCHAR(255) NOT NULL,
FOREIGN KEY("messageId") REFERENCES "MessageModel"("uuid") ON DELETE NO ACTION ON UPDATE CASCADE
);
I can't get why is the err occurs and need help, cause I'm dummy in this ORM.
I'm using "sequelize": "^5.1.0" with SQLite.
MyConfig file:
const Sequelize = require("sequelize");
const electron = require('electron');
const storagePath = electron.app.getPath('userData') + '/plt.db';
module.exports =
development:
dialect: "sqlite",
storage: storagePath,
username: null,
password: null,
operatorsAliases: Sequelize.Op,
define: freezeTableName: true ,
query: raw: true , // Always get raw result
logging: true,
,
;
foreign-keys sequelize.js
add a comment |
I'm using Sequelize.js with SQLite-database and faced a question with setting a value for foreign key. I have the following code:
const MessageModel = sequelize.define('MessageModel ',
uuid: DataTypes.STRING,
authorId: DataTypes.STRING,
// ... other props
, );
const TodoModel = sequelize.define('TodoModel',
ownerId: DataTypes.STRING,
status:
type: DataTypes.STRING,
defaultValue: 'pending'
, );
TodoModel.belongsTo(MessageModel ,
foreignKey:
name: 'messageId',
field: 'messageId',
allowNull: false
,
targetKey: 'uuid'
);
MessageModel.create(
uuid: 'testUUIDForExample'
// other props
).then(message =>
console.log(`Message's created successful`);
TodoModel.create(
ownerId: 'id-string',
status: 'test-status',
messageId: 'testUUIDForExample'
)
)
Sequelize creates MessageModel-row in DB, but it falls when it's trying to generate TodoModel with this err:
DatabaseError: SQLITE_ERROR: foreign key mismatch - "TodoModel" referencing "MessageModel "
at Query.formatError (C:Userslrsvoweb-developmentprojectsplatoon-web-electronnode_modulessequelizelibdialectssqlitequery.js:432:16)
at Query._handleQueryResponse (C:Userslrsvoweb-developmentprojectsplatoon-web-electronnode_modulessequelizelibdialectssqlitequery.js:77:18)
at afterExecute (C:Userslrsvoweb-developmentprojectsplatoon-web-electronnode_modulessequelizelibdialectssqlitequery.js:260:31)
at Statement.errBack (C:Userslrsvoweb-developmentprojectsplatoon-web-electronnode_modulessqlite3libsqlite3.js:16:21)
Err.original.message: "SQLITE_ERROR: foreign key mismatch - "TodoModel" referencing "MessageModel"
Generated SQL:
"INSERT INTO `TodoModel` (`id`,`ownerId`,`status`,`createdAt`,`updatedAt`,`messageId`) VALUES (NULL,$1,$2,$3,$4,$5);"
My TodoModel table looks like:
CREATE TABLE "TodoModel" (
"id" INTEGER PRIMARY KEY AUTOINCREMENT,
"ownerId" VARCHAR(255),
"status" TEXT DEFAULT 'pending',
"createdAt" DATETIME NOT NULL,
"updatedAt" DATETIME NOT NULL,
"messageId" VARCHAR(255) NOT NULL,
FOREIGN KEY("messageId") REFERENCES "MessageModel"("uuid") ON DELETE NO ACTION ON UPDATE CASCADE
);
I can't get why is the err occurs and need help, cause I'm dummy in this ORM.
I'm using "sequelize": "^5.1.0" with SQLite.
MyConfig file:
const Sequelize = require("sequelize");
const electron = require('electron');
const storagePath = electron.app.getPath('userData') + '/plt.db';
module.exports =
development:
dialect: "sqlite",
storage: storagePath,
username: null,
password: null,
operatorsAliases: Sequelize.Op,
define: freezeTableName: true ,
query: raw: true , // Always get raw result
logging: true,
,
;
foreign-keys sequelize.js
I'm using Sequelize.js with SQLite-database and faced a question with setting a value for foreign key. I have the following code:
const MessageModel = sequelize.define('MessageModel ',
uuid: DataTypes.STRING,
authorId: DataTypes.STRING,
// ... other props
, );
const TodoModel = sequelize.define('TodoModel',
ownerId: DataTypes.STRING,
status:
type: DataTypes.STRING,
defaultValue: 'pending'
, );
TodoModel.belongsTo(MessageModel ,
foreignKey:
name: 'messageId',
field: 'messageId',
allowNull: false
,
targetKey: 'uuid'
);
MessageModel.create(
uuid: 'testUUIDForExample'
// other props
).then(message =>
console.log(`Message's created successful`);
TodoModel.create(
ownerId: 'id-string',
status: 'test-status',
messageId: 'testUUIDForExample'
)
)
Sequelize creates MessageModel-row in DB, but it falls when it's trying to generate TodoModel with this err:
DatabaseError: SQLITE_ERROR: foreign key mismatch - "TodoModel" referencing "MessageModel "
at Query.formatError (C:Userslrsvoweb-developmentprojectsplatoon-web-electronnode_modulessequelizelibdialectssqlitequery.js:432:16)
at Query._handleQueryResponse (C:Userslrsvoweb-developmentprojectsplatoon-web-electronnode_modulessequelizelibdialectssqlitequery.js:77:18)
at afterExecute (C:Userslrsvoweb-developmentprojectsplatoon-web-electronnode_modulessequelizelibdialectssqlitequery.js:260:31)
at Statement.errBack (C:Userslrsvoweb-developmentprojectsplatoon-web-electronnode_modulessqlite3libsqlite3.js:16:21)
Err.original.message: "SQLITE_ERROR: foreign key mismatch - "TodoModel" referencing "MessageModel"
Generated SQL:
"INSERT INTO `TodoModel` (`id`,`ownerId`,`status`,`createdAt`,`updatedAt`,`messageId`) VALUES (NULL,$1,$2,$3,$4,$5);"
My TodoModel table looks like:
CREATE TABLE "TodoModel" (
"id" INTEGER PRIMARY KEY AUTOINCREMENT,
"ownerId" VARCHAR(255),
"status" TEXT DEFAULT 'pending',
"createdAt" DATETIME NOT NULL,
"updatedAt" DATETIME NOT NULL,
"messageId" VARCHAR(255) NOT NULL,
FOREIGN KEY("messageId") REFERENCES "MessageModel"("uuid") ON DELETE NO ACTION ON UPDATE CASCADE
);
I can't get why is the err occurs and need help, cause I'm dummy in this ORM.
I'm using "sequelize": "^5.1.0" with SQLite.
MyConfig file:
const Sequelize = require("sequelize");
const electron = require('electron');
const storagePath = electron.app.getPath('userData') + '/plt.db';
module.exports =
development:
dialect: "sqlite",
storage: storagePath,
username: null,
password: null,
operatorsAliases: Sequelize.Op,
define: freezeTableName: true ,
query: raw: true , // Always get raw result
logging: true,
,
;
foreign-keys sequelize.js
foreign-keys sequelize.js
edited Mar 27 at 7:04
Влад Волков
asked Mar 26 at 21:28
Влад ВолковВлад Волков
1186 bronze badges
1186 bronze badges
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
There are a copuple of things here. First If you are going to use uuid
on MessageModel as primary key, you have to define it, otherwise you'll have a default id
field.
const MessageModel = sequelize.define('MessageModel ',
uuid: // if this is your primary key you have to define it
type: DataTypes.STRING, //there is also DataTypes.UUID
allowNull: false,
primaryKey: true,
unique: true
,
authorId: DataTypes.STRING,
// ... other props
, );
Then on your TodoModel, you are setting the messageId
association as integer. To change it to string, you have to define the field on the model, and on the association use it as a foreign key.
const TodoModel = sequelize.define('TodoModel',
ownerId: DataTypes.STRING,
status:
type: DataTypes.STRING,
defaultValue: 'pending'
,
messageId: //you also have to add the field on your model and set it as STRING, because on the association Sequelize by default is going to use INTEGER
type: DataTypes.STRING,
allowNull: false
, );
TodoModel.belongsTo(MessageModel ,
as: 'Message',
foreignKey: 'messageId', // and you only set the foreignKey - Same name as your field above
);
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%2f55366468%2fproblem-with-setting-a-value-in-foreign-key-column%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
There are a copuple of things here. First If you are going to use uuid
on MessageModel as primary key, you have to define it, otherwise you'll have a default id
field.
const MessageModel = sequelize.define('MessageModel ',
uuid: // if this is your primary key you have to define it
type: DataTypes.STRING, //there is also DataTypes.UUID
allowNull: false,
primaryKey: true,
unique: true
,
authorId: DataTypes.STRING,
// ... other props
, );
Then on your TodoModel, you are setting the messageId
association as integer. To change it to string, you have to define the field on the model, and on the association use it as a foreign key.
const TodoModel = sequelize.define('TodoModel',
ownerId: DataTypes.STRING,
status:
type: DataTypes.STRING,
defaultValue: 'pending'
,
messageId: //you also have to add the field on your model and set it as STRING, because on the association Sequelize by default is going to use INTEGER
type: DataTypes.STRING,
allowNull: false
, );
TodoModel.belongsTo(MessageModel ,
as: 'Message',
foreignKey: 'messageId', // and you only set the foreignKey - Same name as your field above
);
add a comment |
There are a copuple of things here. First If you are going to use uuid
on MessageModel as primary key, you have to define it, otherwise you'll have a default id
field.
const MessageModel = sequelize.define('MessageModel ',
uuid: // if this is your primary key you have to define it
type: DataTypes.STRING, //there is also DataTypes.UUID
allowNull: false,
primaryKey: true,
unique: true
,
authorId: DataTypes.STRING,
// ... other props
, );
Then on your TodoModel, you are setting the messageId
association as integer. To change it to string, you have to define the field on the model, and on the association use it as a foreign key.
const TodoModel = sequelize.define('TodoModel',
ownerId: DataTypes.STRING,
status:
type: DataTypes.STRING,
defaultValue: 'pending'
,
messageId: //you also have to add the field on your model and set it as STRING, because on the association Sequelize by default is going to use INTEGER
type: DataTypes.STRING,
allowNull: false
, );
TodoModel.belongsTo(MessageModel ,
as: 'Message',
foreignKey: 'messageId', // and you only set the foreignKey - Same name as your field above
);
add a comment |
There are a copuple of things here. First If you are going to use uuid
on MessageModel as primary key, you have to define it, otherwise you'll have a default id
field.
const MessageModel = sequelize.define('MessageModel ',
uuid: // if this is your primary key you have to define it
type: DataTypes.STRING, //there is also DataTypes.UUID
allowNull: false,
primaryKey: true,
unique: true
,
authorId: DataTypes.STRING,
// ... other props
, );
Then on your TodoModel, you are setting the messageId
association as integer. To change it to string, you have to define the field on the model, and on the association use it as a foreign key.
const TodoModel = sequelize.define('TodoModel',
ownerId: DataTypes.STRING,
status:
type: DataTypes.STRING,
defaultValue: 'pending'
,
messageId: //you also have to add the field on your model and set it as STRING, because on the association Sequelize by default is going to use INTEGER
type: DataTypes.STRING,
allowNull: false
, );
TodoModel.belongsTo(MessageModel ,
as: 'Message',
foreignKey: 'messageId', // and you only set the foreignKey - Same name as your field above
);
There are a copuple of things here. First If you are going to use uuid
on MessageModel as primary key, you have to define it, otherwise you'll have a default id
field.
const MessageModel = sequelize.define('MessageModel ',
uuid: // if this is your primary key you have to define it
type: DataTypes.STRING, //there is also DataTypes.UUID
allowNull: false,
primaryKey: true,
unique: true
,
authorId: DataTypes.STRING,
// ... other props
, );
Then on your TodoModel, you are setting the messageId
association as integer. To change it to string, you have to define the field on the model, and on the association use it as a foreign key.
const TodoModel = sequelize.define('TodoModel',
ownerId: DataTypes.STRING,
status:
type: DataTypes.STRING,
defaultValue: 'pending'
,
messageId: //you also have to add the field on your model and set it as STRING, because on the association Sequelize by default is going to use INTEGER
type: DataTypes.STRING,
allowNull: false
, );
TodoModel.belongsTo(MessageModel ,
as: 'Message',
foreignKey: 'messageId', // and you only set the foreignKey - Same name as your field above
);
answered Mar 27 at 17:43
EllebkeyEllebkey
1,01111 silver badges22 bronze badges
1,01111 silver badges22 bronze badges
add a comment |
add a comment |
Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.
Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.
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%2f55366468%2fproblem-with-setting-a-value-in-foreign-key-column%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