如何使用 Bookshelfjs 保存一对多关系
How to save 1 to many relation with Bookshelfjs
所以我尝试了这个
let Book = bookshelf.Model.extend({tableName: 'book'})
let User = bookshelf.Model.extend({
tableName: 'user',
books: function() {
return this.belongsToMany(Book) // i have table book_user with user_id and book_id fk to respective tables
}
})
return User
然后我尝试使用此代码段进行保存
models.User.forge(myUserObject).save()
.then(function (user) {
return user.books().attach(myBookArray)
})
但它没有像预期的关系对象那样工作 (table book_user
)
我该如何解决这个问题?
我用这段代码修复了它
return Promise.all([
user: saveUser(),
book: saveBook()
])
.then(function (result) {
return result.user.books().attach([result.book.id])
})
所以我尝试了这个
let Book = bookshelf.Model.extend({tableName: 'book'})
let User = bookshelf.Model.extend({
tableName: 'user',
books: function() {
return this.belongsToMany(Book) // i have table book_user with user_id and book_id fk to respective tables
}
})
return User
然后我尝试使用此代码段进行保存
models.User.forge(myUserObject).save()
.then(function (user) {
return user.books().attach(myBookArray)
})
但它没有像预期的关系对象那样工作 (table book_user
)
我该如何解决这个问题?
我用这段代码修复了它
return Promise.all([
user: saveUser(),
book: saveBook()
])
.then(function (result) {
return result.user.books().attach([result.book.id])
})