【问题标题】:Create a object that belongs to two other objects创建一个属于其他两个对象的对象
【发布时间】:2019-04-15 07:25:12
【问题描述】:

我正在使用 sequelize.js V.5 创建一个简单的 api,用于发布书籍的 cmets。评论应该通过图书 id 属于图书,并且对于发布的用户来说也是一样的。

我不太确定如何创建它。

//user model
...
User.hasMany(models.Comment)
...

//book model
...
Book.hasMany(models.Comment);
...

//comment model
...
Comment.belongsTo(models.User);
Comment.belongsTo(models.Book);
...
//route
...
Comment.create(
    {
        //what do i put here? or what other syntax i use
     }
)

【问题讨论】:

    标签: node.js sequelize.js associations


    【解决方案1】:

    根据文档需要关联对象

    直接来自文档的标准示例

    关联对象

    Because Sequelize is doing a lot of magic, you have to call Sequelize.sync after setting the associations! Doing so will allow you the following:
    
    Project.belongsToMany(Task)
    Task.belongsToMany(Project)
    
    Project.create()...
    Task.create()...
    Task.create()...
    
    // save them... and then:
    project.setTasks([task1, task2]).then(function() {
      // saved!
    })
    
    // ok, now they are saved... how do I get them later on?
    project.getTasks().then(function(associatedTasks) {
      // associatedTasks is an array of tasks
    })
    
    // You can also pass filters to the getter method.
    // They are equal to the options you can pass to a usual finder method.
    project.getTasks({ where: 'id > 10' }).then(function(tasks) {
      // tasks with an id greater than 10 :)
    })
    
    // You can also only retrieve certain fields of a associated object.
    project.getTasks({attributes: ['title']}).then(function(tasks) {
        // retrieve tasks with the attributes "title" and "id"
    })
    

    要删除已创建的关联,您只需调用不带特定 id 的 set 方法:

    // remove the association with task1
    project.setTasks([task2]).then(function(associatedTasks) {
      // you will get task2 only
    })
    
    // remove 'em all
    project.setTasks([]).then(function(associatedTasks) {
      // you will get an empty array
    })
    
    // or remove 'em more directly
    project.removeTask(task1).then(function() {
      // it's gone
    })
    
    // and add 'em again
    project.addTask(task1).then(function() {
      // it's back again
    })
    

    至于你的问题:

    一定是这样的:

    Comment.create(
        {
            // create new comment as you like
         }
    

    然后类似(根据需要)

    comment.setUser(user).then(function() {
      // saved!
    })
    
    comment.setBook(book).then(function() {
      // saved!
    })
    

    【讨论】:

    • 这应该可以,但我宁愿使用外键作为非空列,特别是因为所有 cmets 必须与一本书和一个用户相关,作为 PO 约束。我正在寻找一种解决方案,可以同时创建注释并添加外键以防止数据库拒绝数据
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多