插入sequelize.query,然后返回插入的行

And*_*ker 1 postgresql node.js sequelize.js

有没有办法通过sequelize中的原始插入查询返回插入的行?

returning选项不会更改返回值中的任何内容。返回插入行的计数和一个空数组而不是插入的行:[ [], 1 ]

let contato = await sequelize.query(
    'INSERT INTO public.contato(nome, telefone, id_empresa, id_status) VALUES ($nome, $telefone, $id_empresa, $id_status);',
    {
        bind: {
            nome: form.nome,
            telefone: form.telefone,
            id_empresa: filaChat.id_empresa,
            id_status: 1,
        },
        type: QueryTypes.INSERT,
        returning: true,
    }
);
Run Code Online (Sandbox Code Playgroud)

小智 10

对于 postgress,您需要RETURNING id包含在原始查询中。

INSERT INTO public.contato(nome, telefone, id_empresa, id_status)
VALUES ($nome, $telefone, $id_empresa, $id_status)
RETURNING id;
Run Code Online (Sandbox Code Playgroud)

  • 感谢您迟到的答复。它就像一个魅力,使我免于执行其他查询来获取 id。在这种情况下,“returning: true”是没有用的。 (2认同)