【问题标题】:nodejs, sails: creating 2 records of different model at same timenodejs,sails:同时创建2条不同模型的记录
【发布时间】:2018-08-01 05:34:43
【问题描述】:

我有 2 个模型,称为 usersbooks,具有一对多关联。我的架构看起来像

1.模型用户.js

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

book.js 模型

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

一个用户可以包含任意数量的书籍, 我在用户创建表单下添加书籍字段,单击提交按钮时,我需要在用户表和书籍表中创建记录。任何人都可以帮助我如何在控制器中处理相同的事情。提前致谢。

【问题讨论】:

    标签: node.js sails.js sails-mongo


    【解决方案1】:

    您可以通过批量创建来创建您的图书,然后获取您图书的 id,最后创建您的用户。

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-23
      • 2019-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多