sails.js - 模型关联sailsjs中的额外列
问题描述
如何在 postgres 中使用sailsjs 模型关联添加一个额外的列?
这是我的两个模型的一个例子
// Users.js attribute
...
challenges: {
collection: 'challenge',
via: 'userChallenge'
}
// Challenge.js attribute
...
userChallenge: {
collection: 'users',
via: 'challenges'
}
...
有了这个我得到了表关联(多对多)
id | challenge_userChallenge | users_challenges
我需要一个或多个额外的列,例如“活动”或类似的内容
提前致谢
解决方案
你应该使用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
模型实际上是连接表。在此模型中,您可以定义额外的字段。
希望这可以帮助。
推荐阅读
- azure - 将 Azure 订阅转移到另一个租户后,是否可以恢复 RBAC/用户?
- java - 如何创建 Spring Boot REST 服务“类型:POST”?
- reactjs - 玩 Babel ^7.0.0-rc.1 问题
- java - 为什么不显示使用 PDFBox(2.0.11) 设置的表单域?
- html - 如何将此表格和按钮放在图像旁边(图像右侧)
- c# - 调试异步等待方法 C#
- domain-driven-design - 如何处理(部分)依赖聚合根?
- database - Laravel onDelete('cascade') 有效,除了一个关系
- c - 生产者消费者同步使用两个线程提供异常的串行输出
- javascript - 使用 Nodejs 从 API 自动获取数据