在 sequelize.query 中插入,然后在 return 中插入插入的行

Insert in sequelize.query and then return the inserted row

有没有办法在 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,
    }
);

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

INSERT INTO public.contato(nome, telefone, id_empresa, id_status)
VALUES ($nome, $telefone, $id_empresa, $id_status)
RETURNING id;