如何在bookshelf.js中同时插入父表和子表

4

我有一张名为companies的表和另一张名为companies_posts的表,其中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一样。还是我需要先插入公司,获得lastInsertId,然后在其后插入每个公司文章?
谢谢。
编辑:(顺便说一下,我刚学会使用withRelatedhasMany进行选择。现在我必须学习如何插入/更新
1个回答

2

不,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
    });
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接