如何在 bookshelf.js 中同时插入父表和子表
How to insert into parent and child tables at once in bookshelf.js
我有一个名为 companies
的 table 和一个名为 companies_posts
的 company_posts.company_id
,其中 company_posts.company_id
是 companies.id
的外键
假设我得到以下 json
:
{
"name" : "Teste",
"username" : "teste1",
"password" : "teste1",
"email" : "teste2@teste",
"photo" : "teste",
"description" : "teste",
"company_posts" : [
{"text" : "oi"},
{"text" : "olá"}
]
}
bookshelf.js
有什么方法可以一次性插入吗?我想像 mongodb。或者我需要 insert company
、lastInsertId
然后 insert
每个 company_posts
之后?
谢谢。
编辑:(顺便说一句,我刚刚学会了如何使用 withRelated
和 hasMany
来 select
。现在我必须学习如何 insert
/ update
)
不是,bookshelf.js使用的是knex.js,它是基于关系数据库的。因此,您必须首先插入公司。在回调函数中你得到插入的id,你也可以插入帖子。
你当然可以为此使用交易,这在最近 knex.js 的更新中得到了很大的改进。
我还没有测试过这个,但我认为类似的东西应该或多或少有用:
var Company = bookshelf.Model.extend({
tableName: 'companies',
posts: function(){
return this.hasMany(Post);
}
});
var Post = bookshelf.Model.extend({
tableName: 'posts',
companies: function(){
return this.belongsTo(Company);
}
});
new Company().save({...}).then(function(company){
new Post().save({
...
company_id: company.get('id')
}).then(function(post){
//final result
});
});
我有一个名为 companies
的 table 和一个名为 companies_posts
的 company_posts.company_id
,其中 company_posts.company_id
是 companies.id
假设我得到以下 json
:
{
"name" : "Teste",
"username" : "teste1",
"password" : "teste1",
"email" : "teste2@teste",
"photo" : "teste",
"description" : "teste",
"company_posts" : [
{"text" : "oi"},
{"text" : "olá"}
]
}
bookshelf.js
有什么方法可以一次性插入吗?我想像 mongodb。或者我需要 insert company
、lastInsertId
然后 insert
每个 company_posts
之后?
谢谢。
编辑:(顺便说一句,我刚刚学会了如何使用 withRelated
和 hasMany
来 select
。现在我必须学习如何 insert
/ update
)
不是,bookshelf.js使用的是knex.js,它是基于关系数据库的。因此,您必须首先插入公司。在回调函数中你得到插入的id,你也可以插入帖子。
你当然可以为此使用交易,这在最近 knex.js 的更新中得到了很大的改进。
我还没有测试过这个,但我认为类似的东西应该或多或少有用:
var Company = bookshelf.Model.extend({
tableName: 'companies',
posts: function(){
return this.hasMany(Post);
}
});
var Post = bookshelf.Model.extend({
tableName: 'posts',
companies: function(){
return this.belongsTo(Company);
}
});
new Company().save({...}).then(function(company){
new Post().save({
...
company_id: company.get('id')
}).then(function(post){
//final result
});
});