【问题标题】:One to One or Many to One in sequelize?续集中是一对一还是多对一?
【发布时间】:2018-07-02 17:42:28
【问题描述】:

我正在使用 sequelize 和 mssql。

我尝试创建一对一关系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]';

问题依然存在。

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 我做了Player.hasOne(Team); Team.hasOne(Player);,但出现错误:cyclic dependency found. players is dependent of itself.``Dependency chain: players -> teams => players
    • 当然那样会导致递归。你只需要 Player.hasOne(Team) 我强烈建议你阅读文档来学习 a,b,c。
    • 相同。我阅读了它的文档。但是,它仍然没有按预期工作。
    【解决方案2】:

    根据后续docs,当源模型中存在关联信息时,您可以使用“belongsTo”,当目标模型中存在关联信息时,您可以使用“hasOne”。

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-30
      • 2021-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多