【问题标题】:How to setup belongsToMany Relation with additionnal attribute in the join table in featherjs with feather-sequelize如何使用feather-sequelize在feathersjs的连接表中设置belongsToMany关系和附加属性
【发布时间】:2019-01-09 21:34:50
【问题描述】:

我想在两个模型之间添加多对多关系,并在连接表中添加附加属性。 sequelize 的文档很清楚:我必须创建一个我喜欢的使用的新模型

const User = sequelize.define('user', {})
const Project = sequelize.define('project', {})
const UserProjects = sequelize.define('userProjects', {
    status: DataTypes.STRING
})

User.belongsToMany(Project, { through: UserProjects })
Project.belongsToMany(User, { through: UserProjects })

但是当我在我的羽毛应用程序中定义一个新模型时,它没有在数据库中创建,所以我的关系不起作用

【问题讨论】:

    标签: sequelize.js feathersjs feathers-sequelize


    【解决方案1】:

    只是为了检查我是否理解正确:您想要一个链接表(例如user_projects),并将UserProjects 模型映射到它,从而在UserProject模特?

    您可以使用hasManybelongsTo 函数,而不是belongsToMany,例如:

    User.hasMany(UserProjects, {
      as: 'UserProjects',
      foreignKey: 'user_id' // this is what you're missing
    });
    Project.hasMany(UserProjects, {
      as: 'UserProjects',
      foreignKey: 'project_id' // this is what you're missing
    });
    
    UserProjects.belongsTo(User, {
      as: 'Users',
      foreignKey: 'user_id'
    });
    UserProjects.belongsTo(Projects, {
      as: 'Projects',
      foreignKey: 'project_id'
    });
    

    您需要将链接表中的user_idproject_id 列定义为外键。

    然后你可以在你的链接表中添加你想要的任何其他属性(status 或其他任何东西,没关系)

    【讨论】:

      猜你喜欢
      • 2018-08-18
      • 1970-01-01
      • 1970-01-01
      • 2018-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多