获取最后插入的 id Sequelize

编程入门 行业动态 更新时间:2024-10-26 12:23:22
本文介绍了获取最后插入的 id Sequelize的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用 Sequelize 并且我正在尝试获取原始查询中最后插入的 ID.

I'm using Sequelize and I'm trying to get the last inserted ID in raw query.

我的查询是

.query(Sequelize.Utils.format(["insert into MyTable (field1, field2) values (?,?)", val1, val2])

查询完成,但成功事件的结果为null.

The query is done perfectly, but the result on success event is null.

有人可以帮忙吗?

谢谢.

经过一些研究和无数次尝试,我了解了被调用对象在 sequelizeJs 中的工作原理.

After some researches and zillions attempts, I understood how callee object work in sequelizeJs.

如果我的回答有误,请纠正我.

please, correct me if my answer is wrong.

被调用对象需要这个结构

the callee object needs this structure

{__factory:{autoIncrementField: 'parameterName'}, parameterName: '' }

在这种情况下是参数名称"是将存储新 ID 的字段,sequelize 查找 __factory.autoIncrementField 以将最后插入的 id 的值设置为其值(__factory.autoIncrementField 的值).

in this case "parameterName" is the field that will store the new ID, sequelize looks for __factory.autoIncrementField to set value of last inserted id into property with its value (value of __factory.autoIncrementField).

所以,我对查询方法的调用是

so, my call to querys method would be

.query(sequelize.Utils.format(tempInsert), {__factory:{autoIncrementField: 'parameterName'}, parameterName: '' }, {raw: true})

这将导致这样的对象

{ __factory: { autoIncrementField: 'parameterName' }, parameterName: newInserted_ID }

谢谢大家,我希望这可以帮助某人.

thanks for all, and I hope this can help someone.

推荐答案

是的,您的答案奏效了.另一种方式是

Yes your answer is working. Another way would be

var Sequelize = require("sequelize") var sequelize = new Sequelize('test', 'root', 'root', {dialect: 'mysql'}) var Page = sequelize.define( 'page', { type : {type: Sequelize.STRING(20)}, order : {type: Sequelize.INTEGER, defaultValue: 1} },{ timestamps: false, underscored: true }) Page.__factory = {autoIncrementField: 'id'} Page.id = '' sequelize.query('INSERT INTO pages SET `type` = ?, `order` = ?, `topic_version_id` = ?', Page, {raw: false}, ['TEXT', 1, 1] ).success(function(page) { console.log(page) Page.find(page.id) .success(function(result){ console.log(result) }) })

更多推荐

获取最后插入的 id Sequelize

本文发布于:2023-10-13 20:43:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1489023.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:id   Sequelize

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!