是一对一还是多对一?

时间:2018-07-02 17:42:28

标签: javascript sql node.js database sequelize.js

我在MSSQL中使用sequelize

我尝试创建一对一关系like in this picture

所以我使用了sequelize docs中的代码:

const Player = this.sequelize.define('player', {/* attributes */});
const Team  = this.sequelize.define('team', {/* attributes */});

Player.belongsTo(Team); // Will add a teamId attribute to Player to hold the primary key value for Team

我得到了多对一as you can see in the picture

所以我尝试做:

const Player = sequelize.define('player', { /* attributes */ });
const Team  = sequelize.define('team', { /* attributes */ });

Player.belongsTo(Team);
Team.hasOne(Player);

结果相同。

如何建立一对一关系?

修改

对于此代码:

const Player = sequelize.define('player', { /* attributes */ });
const Team  = sequelize.define('team', { /* attributes */ });

Player.hasOne(Team);

这是sequelize的作用:

IF OBJECT_ID('[teams]', 'U') IS NOT NULL DROP TABLE [teams];
IF OBJECT_ID('[players]', 'U') IS NOT NULL DROP TABLE [players];
IF OBJECT_ID('[players]', 'U') IS NOT NULL DROP TABLE [players];
IF OBJECT_ID('[players]', 'U') IS NULL CREATE TABLE [players] ([id] INTEGER NOT NULL IDENTITY(1,1) , [createdAt] DATETIMEOFFSET NOT NULL, [updatedAt] DATETIMEOFFSET NOT NULL, PRIMARY KEY ([id]));
EXEC sys.sp_helpindex @objname = N'[players]';
IF OBJECT_ID('[teams]', 'U') IS NOT NULL DROP TABLE [teams];
IF OBJECT_ID('[teams]', 'U') IS NULL CREATE TABLE [teams] ([id] INTEGER NOT NULL IDENTITY(1,1) , [createdAt] DATETIMEOFFSET NOT NULL, [updatedAt] DATETIMEOFFSET NOT NULL, [playerId] INTEGER NULL, PRIMARY KEY ([id]), FOREIGN KEY ([playerId]) REFERENCES [players] ([id]) ON DELETE SET NULL);
EXEC sys.sp_helpindex @objname = N'[teams]';

问题仍然存在。

2 个答案:

答案 0 :(得分:0)

您应该使用hasOne()方法。不是belongsTo()就是这样:)

答案 1 :(得分:0)

按照docs的顺序,当源模型中存在关联信息时,可以使用“ belongsTo”,而目标模型中存在关联信息时,可以使用“ hasOne”。

在您的情况下,有关关联的信息存在于源模型中(teamId存在于团队模型中),因此您应该做的是:

Team.belongsTo(Player)
Player.hasOne(Team)

您在编辑后的答案中所做的操作是正确的,应该足够了。