首页 > 解决方案 > 模型关联sailsjs中的额外列

问题描述

如何在 postgres 中使用sailsjs 模型关联添加一个额外的列?

这是我的两个模型的一个例子

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


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

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

 id | challenge_userChallenge | users_challenges 

我需要一个或多个额外的列,例如“活动”或类似的内容

提前致谢

标签: sails.jssails-postgresql

解决方案


你应该使用through associations

多对多直通关联的行为方式与多对多关联相同,但连接表会自动为您创建。在多对多直通关联中,您定义了一个模型,其中包含两个字段,这些字段对应于您将要连接在一起的两个模型。定义关联时,您将添加 through 键以显示应该使用模型而不是自动连接表。

我们以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型号:

/**
 * 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模型实际上是连接表。在此模型中,您可以定义额外的字段。

希望这可以帮助。


推荐阅读