How to insert into parent and child tables immediately in bookshelf.js

I have a table called companies, and the other is companies_posts, where company_posts.company_idis the foreign key forcompanies.id

Suppose I got the following json:

  {

       "name" : "Teste",
       "username" : "teste1",
       "password" : "teste1",
       "email" : "teste2@teste",
       "photo" : "teste",
       "description" : "teste",
       "company_posts" : [
          {"text" : "oi"},
          {"text" : "olá"}
       ]

   }

Is there a way in bookshelf.jsto insert it right away? I guess like a mongodb. Or do I need insert companyto receive lastInsertId, and then inserteach company_postsimmediately after?

Thank.

Edit: (By the way, I just learned selectusing withRelatedand hasMany. Now I have to find out how insert/ update)

+4
source share
1 answer

, bookshelf.js knex.js, . , . , .

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

Source: https://habr.com/ru/post/1589010/


All Articles