你应该使用through associations。
多对多直通关联的行为方式与多对多关联相同,但连接表会自动为您创建。在多对多直通关联中,您定义了一个模型,其中包含两个字段,这些字段对应于您将要连接在一起的两个模型。定义关联时,您将添加 through 键以显示应该使用模型而不是自动连接表。
我们以Post
和Tag
模型为例。拥有Post
并属于许多人Tag
,Tag
拥有并属于许多人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
型号:
/**
* 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
模型实际上是连接表。在此模型中,您可以定义额外的字段。
希望这可以帮助。