gpt4 book ai didi

node.js - 创建一个属于另外两个对象的对象

转载 作者:行者123 更新时间:2023-12-03 22:37:56 25 4
gpt4 key购买 nike

我正在使用 sequelize.js V.5 创建一个简单的 api 来发布书籍评论。评论应该通过图书 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
}
)

最佳答案

根据文档,您需要关联对象

直接来自文档的标准示例

关联对象

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 方法而无需特定 ID:
// 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!
})

关于node.js - 创建一个属于另外两个对象的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55679237/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com