Создать объект, который принадлежит двум другим объектам - PullRequest
0 голосов
/ 14 апреля 2019

Я создаю простой API, используя sequelize.js V.5 для публикации комментариев книг. Комментарий должен принадлежать книге через идентификатор книги и такой же для пользователя, который разместил.

Я не совсем уверен, как это создать.

//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
     }
)

1 Ответ

0 голосов
/ 15 апреля 2019

Согласно документу вам необходимо связать объекты

Стандартный пример прямо из документа

Связывающие объекты

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"
})

Чтобы удалить созданные ассоциации, вы можете просто вызвать метод 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!
})
...