模型关联sailsjs中的额外列

sus*_*ind 2 sails.js sails-postgresql

如何在带有sailsjs模型关联的postgres中多出一列?

这是我的两个模型的示例

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


// Challenge.js attribute
...
userChallenge: {
  collection: 'users',
  via: 'challenges'
}
...
Run Code Online (Sandbox Code Playgroud)

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

 id | challenge_userChallenge | users_challenges 
Run Code Online (Sandbox Code Playgroud)

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

提前致谢

Vla*_*rak 5

您应该通过关联使用。

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

我们以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'
    }

};
Run Code Online (Sandbox Code Playgroud)

我们的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'
    }

  }

};
Run Code Online (Sandbox Code Playgroud)

我们的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'
    }

  }

};
Run Code Online (Sandbox Code Playgroud)

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

希望这可以帮助。