gpt4 book ai didi

sails.js - 模型关联 sailsjs 中的额外列

转载 作者:行者123 更新时间:2023-12-02 17:08:39 24 4
gpt4 key购买 nike

如何在带有 sailsjs 模型关联的 postgres 中有一个额外的列?

这是我的两个模型的例子

// Users.js attribute
...
challenges: {
collection: 'challenge',
via: 'userChallenge'
}


// Challenge.js attribute
...
userChallenge: {
collection: 'users',
via: 'challenges'
}
...

有了这个,我得到了表关联(多对多)

 id | challenge_userChallenge | users_challenges 

我需要一个或多个额外的列,如“活跃”或类似的东西

提前致谢

最佳答案

你应该使用 through associations .

Many-to-Many through associations behave the same way as many-to-many associations with the exception of the join table being automatically created for you. In a Many-To-Many through assocation you define a model containing two fields that correspond to the two models you will be joining together. When defining an association you will add the through key to show that the model should be used rather than the automatic join table.

我们以PostTag 模型为例。 Post 拥有并属于许多 TagTag 拥有并属于许多 Post。这两个模型将通过 PostTag 模型连接。

我们的 Post 模型:

/**
* Post.js
*
* @description :: A model definition. Represents a database table/collection/etc.
* @docs :: https://sailsjs.com/docs/concepts/models-and-orm/models
*/

module.exports = {

tableName: 'posts',

attributes: {

name: {
type: 'string',
required: true
},

// Many to many: Post has and belongs to many Tag.
tags: {
collection: 'Tag',
via: 'postId',
through: 'PostTag'
}

};

我们的标签模型:

/**
* Tag.js
*
* @description :: A model definition. Represents a database table/collection/etc.
* @docs :: https://sailsjs.com/docs/concepts/models-and-orm/models
*/

module.exports = {

tableName: 'tags',

attributes: {

name: {
type: 'string',
unique: true,
required: true
},

// Many to many: Tag has and belongs to many Post.
posts: {
collection: 'Post',
via: 'tagId',
through: 'PostTag'
}

}

};

我们的 PostTag 模型(我们手动创建它,我们不希望 Sails.js 自动创建它):

/**
* PostTag.js
*
* @description :: A model definition. Represents a database table/collection/etc.
* @docs :: https://sailsjs.com/docs/concepts/models-and-orm/models
*/

module.exports = {

tableName: 'posts_tags',

attributes: {

postId: {
model: 'Post'
},

tagId: {
model: 'Tag'
}

}

};

PostTag 模型实际上就是连接表。在此模型中,您可以定义额外的字段。

希望这对您有所帮助。

关于sails.js - 模型关联 sailsjs 中的额外列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50436124/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com