简体   繁体   English

是一对一还是多对一?

[英]One to One or Many to One in sequelize?

I'm using sequelize with mssql. 我正在使用mssql的续集

I try to create One-to-One relation like in this picture : 我尝试创建如下图所示的一对一关系:

So I use the code from sequelize docs: 所以我使用了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

I got Many-To-One as you can see in the picture 我得到了许多对一,你可以在图片中看到

So I have try to do: 所以我尝试做:

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

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

Same result. 结果相同。

How can I do one-to-one relation? 如何建立一对一关系?

Edit 编辑

For this code: 对于此代码:

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

Player.hasOne(Team);

This is what sequelize does: 这是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]';

And still the problem exist. 而且问题仍然存在。

You should use hasOne() method. 您应该使用hasOne()方法。 not belongsTo() that's it :) belongsTo() :)

According to sequelize docs you can use "belongsTo" when information about association is present in the source model and "hasOne" when information about association is present in the target model. 根据sequelize docs ,当源模型中存在有关关联的信息时,可以使用“ belongsTo”;如果目标模型中存在有关关联的信息,则可以使用“ hasOne”。

In your case, the information about association is present in the source model (playerId exists on the team model) thus what you should do is: 在您的情况下,有关关联的信息存在于源模型中(teamId存在于团队模型中),因此您应该做的是:

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

and what you did in the edited answer is correct and should suffice. 并且您在编辑后的答案中所做的操作是正确的,应该足够了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM