Node.js 如何使用knex将Json数据的子集插入SQLite3细节表
这是我使用NodeJs的第一步,我来自一种顺序结构语言 在开发我的API时,我遇到了一个我认为很简单的情况,但我不确定如何处理它 我有一个Json(见下文),其中包含要包含在“Organizao”表中的主要数据。在同一个json中,我有一个节点,其中包含数据“tags”的子集,必须包含在另一个名为“organizao_tag”的表中,采用master/detail样式 我想知道如何在detail表中执行此包含,该表仅由“id_organizacao”+“id_tag”组成。我相信有一个简单的方法像第一次插入,但我怀疑如何对待它 我使用sqlite3数据库、nodeJS、knex和事务的概念 以下是收到的Json和完整代码: Json: 代码: 谢谢你的支持Node.js 如何使用knex将Json数据的子集插入SQLite3细节表,node.js,api,express,knex.js,Node.js,Api,Express,Knex.js,这是我使用NodeJs的第一步,我来自一种顺序结构语言 在开发我的API时,我遇到了一个我认为很简单的情况,但我不确定如何处理它 我有一个Json(见下文),其中包含要包含在“Organizao”表中的主要数据。在同一个json中,我有一个节点,其中包含数据“tags”的子集,必须包含在另一个名为“organizao_tag”的表中,采用master/detail样式 我想知道如何在detail表中执行此包含,该表仅由“id_organizacao”+“id_tag”组成。我相信有一个简单的方法
{
"razaosocial_org": "Bela Fashion Studio",
"atividade_org": 1,
"endereco_org": "Av. Brasil",
"complemento_org": "Loja 1",
"numero_org": "1000",
"bairro_org": "Centro",
"cep_org": "12345-001",
"cidade_org": 1,
"descricao_cidade_org": "Rio de Janeiro",
"uf_org": "RJ",
"fisico_juridico_org": 0,
"cpf_cnpj_org": "25722123000100",
"telefone_org": "(32) 1234-5378",
"celular_org": "(32) 1234-5378",
"tags": [
{ "id": 11, "tag": "CABELEIREIRO"},
{ "id": 12, "tag": "SALAO DE BELEZA"},
{ "id": 13, "tag": "STUDIO DE BELEZA"}
]
}
import { Request, Response } from 'express';
import knex from 'knex';
import db from '../database/connections';
export default class OrganizacoesController{
async create(req: Request, res: Response) {
const {
razaosocial_org,
atividade_org,
endereco_org,
complemento_org,
numero_org,
bairro_org,
cep_org,
cidade_org,
descricao_cidade_org,
uf_org,
fisico_juridico_org,
cpf_cnpj_org,
telefone_org,
celular_org,
tags
} = req.body;
const trx = await db.transaction();
try {
const OrganizacaoInserted = await trx('organizacao').insert({
razaosocial_org,
atividade_org,
endereco_org,
complemento_org,
numero_org,
bairro_org,
cep_org,
cidade_org,
descricao_cidade_org,
uf_org,
fisico_juridico_org,
cpf_cnpj_org,
telefone_org,
celular_org
});
const organizacao_Id = OrganizacaoInserted[0];
//----------------------------------- x ---------------------------------
// ===>>> Here is the big question, how to get the subset of data contained in "tags" and insert it in the "organizacao_tag" table"
// const OrganizacaoTagInserted = await trx('organizacao_tag').insert({
// organizacao_Id,
// ????,
// });
//----------------------------------- x ---------------------------------
await trx.commit();
return res.status(201).send();
} catch (err) {
console.log(err);
await trx.rollback();
return res.status(400).json({
error: 'Unexpected error when inserting new organization: ' + err
});
}
return res.send();
};
};