-1

I have 2 models called users and books with one to many associations. My schema looks like

1. model user.js

module.exports = {
  attributes: {
    userName: {
      type: 'string'
    },
    books: {
      type: 'ref',
      columnType: 'book',
      via: 'userBooks'
    }

book.js model

attributes: {
    bookName: {
      type: 'string'
    },
    userBooks: {
      model: 'user'
    }

A user may contains any number of books, I am adding fields of books under user create form, on clicking submit button I need to create records in both user table and book table. Can anyone help me how we can handle the same in controller. Thanks in advance.

Manish Balodia
  • 1,863
  • 2
  • 23
  • 37
krishna m
  • 73
  • 1
  • 7

1 Answers1

0

You can create yours books with a bulk create, then get the id of yours books and finally create your user.

var books = await Book.createEach(req.param('books')).fetch();
if(books){
     var ids = books.map(b => b.id); //get all the id attribute from book object
     var user = await User.create({ userName: req.param('userName'), books: ids});
}

https://sailsjs.com/documentation/reference/waterline-orm/queries/fetch https://sailsjs.com/documentation/reference/waterline-orm/models/create-each https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Array/map

Lucas Penén
  • 41
  • 2
  • 6