我只是尝试运行您的代码,并且行似乎创建得很好:
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
In short belongsTo
adds the relation to the table that you are calling the method on, hasOne
adds it on the table that is given as argument.