[英]Sequelize.js foreign key
使用 Sequelize.js 時,以下代碼不會在表上添加任何外鍵。
var MainDashboard = sequelize.define('main_dashboard', {
title: Sequelize.STRING
}, {
freezeTableName: true
})
MainClient.hasOne(MainDashboard, { foreignKey: 'idClient' })
MainDashboard.hasOne(MainClient, { foreignKey: 'clientId' })
sequelize.sync({ force: true })
有沒有辦法強制 Sequelize.js 添加這些外鍵約束?
在我遇到同樣的問題之前,當我了解設置 Sequelize 的功能后就解決了。
開門見山!
假設我們有兩個目標:人與父親
var Person = sequelize.define('Person', {
name: Sequelize.STRING
});
var Father = sequelize.define('Father', {
age: Sequelize.STRING,
//The magic start here
personId: {
type: Sequelize.INTEGER,
references: 'persons', // <<< Note, its table's name, not object name
referencesKey: 'id' // <<< Note, its a column name
}
});
Person.hasMany(Father); // Set one to many relationship
也許它可以幫助你
編輯:
您可以閱讀本文以更好地理解:
http://docs.sequelizejs.com/manual/tutorial/associations.html#foreign-keys
對於 Sequelize 4,這已更新為以下內容:
const Father = sequelize.define('Father', {
name: Sequelize.STRING
});
const Child = sequelize.define('Child', {
age: Sequelize.STRING,
fatherId: {
type: Sequelize.INTEGER,
references: {
model: 'fathers', // 'fathers' refers to table name
key: 'id', // 'id' refers to column name in fathers table
}
}
});
Father.hasMany(Child); // Set one to many relationship
編輯:您可以在https://sequelize.org/master/manual/assocs.html上閱讀有關關聯的更多信息
您需要添加foreignKeyConstraint: true
嘗試:
MainClient.hasOne(MainDashboard, { foreignKey: 'idClient', foreignKeyConstraint: true })
我只是嘗試運行您的代碼,行似乎創建得很好:
CREATE TABLE IF NOT EXISTS `main_dashboard` (`title` VARCHAR(255), `id` INTEGER NOT NULL auto_increment , `idClient` INTEGER, PRIMARY KEY (`id`)) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS `main_client` (`id` INTEGER NOT NULL auto_increment, `clientId` INTEGER, PRIMARY KEY (`id`)) ENGINE=InnoDB;
clientId
添加到main_client
, idClient
添加到main_dashboard
您似乎對hasOne
方法的作用有些困惑。 每次調用hasOne
都會創建一個關聯,因此您的代碼將兩個表有效地關聯了兩次。 您正在尋找的方法是belongsTo
如果您希望每個客戶端都有一個儀表板,則代碼如下:
MainClient.hasOne(MainDashboard, { foreignKey: 'clientId' })
MainDashboard.belongsTo(MainClient, { foreignKey: 'clientId' })
這就產生了一個clientId
場上main_dashboard
表,該表涉及id
的場main_client
表
簡而言之, belongsTo
將關系添加到您正在調用該方法的表中, hasOne
將其添加到作為參數給出的表中。
這非常簡單。
const MainDashboard = this.sequelize.define('main_dashboard', {/* attributes */})
, MainClient = this.sequelize.define('main_client', {/* attributes */});
MainDashboard.belongsTo(MainClient, { foreignKey: 'clientId' }); // Adds clientId to MainDashboard
它將將此鏈接為外鍵,您可以將其用作關聯。 如果我遺漏了什么,請告訴我。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.