Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 views
in Technique[技术] by (71.8m points)

node.js - 划分同一类的两个关系(Sequelize two relationships of the same class)

Hello I have a question about sequelize

(您好,我有关于续集的问题)

I have two entities two models

(我有两个实体两个模型)

users and match

(用户和匹配)

a match has two users

(一场比赛有两个用户)

my doubt how I would make this relationship

(我怀疑我将如何建立这种关系)

I would have to for two user_id?

(我必须要两个user_id?)

my match would basically have

(我的比赛基本上)

match id, player id one, player id two

(比赛ID,玩家ID一,玩家ID二)

I doubt how to relate or define this in sequelize

(我怀疑如何关联或定义这个)

  ask by Felipe translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can define match as following.

(您可以按以下方式定义匹配。)

I assume you have UserModel.id as Seqeulize.INTEGER .

(我假设您有UserModel.id作为Seqeulize.INTEGER 。)

const MatchModel = Sequelize.define("Match", {
    // ... Other column declaration

    // Two user column -- which are not linked yet.
    playerOneId: {
        type: Sequelize.INTEGER,
        allowNull: false
    },
    playerTwoId: {
        type: Sequelize.INTEGER,
        allowNull: false
    }
})

// Now time to link the UserModel
// I assume you have `UserModel` declared before doing this.
MatchModel.belongsTo(UserModel, {
    foreignKey: {
        name: "playerOneId"
    },
    as: "playerOne"
}

MatchModel.belongsTo(UserModel, {
    foreignKey: {
        name: "playerTwoId"
    },
    as: "playerTwo"
}

Now while query a MatchModel do following

(现在,在查询MatchModel请执行以下操作)

MatchModel.findOne({
    where: {
         // Your condition goes here
    },
    includes: [
        {
             model: UserModel,
             as: "playerOne"
        },
        {
             model: UserModel,
             as: "playerTwo"
        },
    ]
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...