【问题标题】:How to insert into parent and child tables at once in bookshelf.js如何在 bookshelf.js 中一次插入父表和子表
【发布时间】:2015-05-20 13:26:39
【问题描述】:

我有一个名为companies 的表和另一个名为companies_posts 的表,其中company_posts.company_idcompanies.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

谢谢。

编辑:(顺便说一句,我刚刚学会了如何使用withRelatedhasManyselect。现在我必须学习如何insert / update

【问题讨论】:

    标签: mysql node.js bookshelf.js


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2015-05-14
      • 1970-01-01
      • 2011-11-06
      • 1970-01-01
      • 2020-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多