logo
down
shadow

return last inserted id sequelize


return last inserted id sequelize

By : solmonta
Date : November 28 2020, 09:01 AM
it should still fix some issue Actually the promise function returns the newly created row, but for some reason I could only see [1] at my console, now I see the object.
code :
.then( function ( x ) {

    //x = new created row
    response.json( x );

} );


Share : facebook icon twitter icon
Get last inserted id Sequelize

Get last inserted id Sequelize


By : santhosh
Date : March 29 2020, 07:55 AM
wish of those help I'm using Sequelize and I'm trying to get the last inserted ID in raw query. , Yes your answer is working. Another way would be
code :
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)
    })

})
Get id of inserted row from upsert (insertOrUpdate) Sequelize Node.js

Get id of inserted row from upsert (insertOrUpdate) Sequelize Node.js


By : yogda
Date : March 29 2020, 07:55 AM
like below fixes the issue Getting the ID back from upsert in Sequelize is not possible at the moment. For more information see: https://github.com/sequelize/sequelize/issues/3354
A possible solution to this issue is to force the user (or the REST API client in this case) to supply the ID of a record in case update is requested, and to not supply an ID in case of creating a new record. This is generally a good idea as it prevents a round trip to the DB, though it makes your API a bit more strict.
Define Sequelize model such as all inserted entries should be in lowercase

Define Sequelize model such as all inserted entries should be in lowercase


By : Tuti Herlina
Date : March 29 2020, 07:55 AM
Hope that helps What you're looking for is beforeCreate() sequelize hook:
code :
const Users = sequelize.define('users', {
        id: {
            type: Sequelize.INTEGER,
            primaryKey: true,
        },
        mobile : {
            type: Sequelize.STRING,
        }
        first_name: {
            type: Sequelize.STRING,

        },
        last_name :{
            type: Sequelize.STRING,
        },
        email :{
            type: Sequelize.STRING,
        }
    },
    {
        freezeTableName: true
    },
    hooks: {
        beforeCreate: function(user){

            user.first_name = user.first_name.toLowerCase();
            user.last_name  = user.last_name.toLowerCase();

            return user;

        }
    }

);
GraphQL and Sequelize doesn't return inserted object

GraphQL and Sequelize doesn't return inserted object


By : user7911868
Date : March 29 2020, 07:55 AM
hope this fix your issue I'm stuck on an error on my GraphQL and Sequelize backend, for some reason my mutation doesn't return the data, even though I guarantee there's data being returned inside my resolver. I feel like this is probably something small that I'm missing, but I've been stuck for awhile. , You're missing three returns:
code :
createUserVoucher: (parent, args, { user, models }) => {
  args['userId'] = user.id;
  return models.UserVoucher.count({ <----- HERE
    where: {utilized: true, pinId: args.pinId, userId: args.userId}
  }).then( c => {
    if (c > 0) {
      return []
    } else {
      return models.Voucher.findOne({ // <----- HERE
        where: {
          id: args.voucherId
        }
      }).then( voucher => {
        return models.UserVoucher.count({ // <----- AND HERE
          where: { voucherId: args.voucherId }
        }).then( c => {
            return models.UserVoucher.create(args)
        })
      })
    }
  });
  return []
}
createUserVoucher: async (parent, args, { user, models }) => {
  args['userId'] = user.id;
  const c = await models.UserVoucher.count({
    where: {utilized: true, pinId: args.pinId, userId: args.userId}
  })
  if (c > 0) return null
  const voucher = await models.Voucher.findOne({
    where: { id: args.voucherId }
  })
  const c2 = await models.UserVoucher.count({ 
    where: { voucherId: args.voucherId }
  })
  return models.UserVoucher.create(args) // still need a return here
}
Is it possible to get the inserted row's ID using hooks in sequelize?

Is it possible to get the inserted row's ID using hooks in sequelize?


By : vicky
Date : March 29 2020, 07:55 AM
wish help you to fix your issue I tried below method and I discovered a lot of things that can be done inside a model definition.
code :
'use strict';
module.exports = (sequelize, DataTypes) => {
 const Order = sequelize.define('Order', {
   buyer_id: DataTypes.INTEGER.UNSIGNED,
   order_status_code: DataTypes.TINYINT.UNSIGNED,
   order_detail: DataTypes.TEXT,
   order_date: DataTypes.DATE,
   order_number: DataTypes.STRING(20)
 }, {
   hooks:{
     afterCreate:  async function(order, options) {
     await order.update(
       {
         order_number : 'OD' + Date.now() + order.id + order.OrderItem.product_id + order.buyer_id
       },
       {
         transaction: options.transaction
       })
     }
   }
  });
 Order.associate = function(models) {
   // associations can be defined here
   Order.hasOne(models.OrderItem,{foreignKey: "order_id"})
 };
 return Order;
};
Related Posts Related Posts :
  • How to get maximum number of products matched vendors list. But i don't want to check same products again
  • Get the data from related tables (models) sequelize
  • MYsql INSERT ON DUPLICATE KEY UPDATE with IF
  • Why mysql gives result with postfix zeros
  • SQL : Search column value using IN clause
  • Dreamfactory : How to use MySQL aggregate functions in queries
  • AND not working with Nested Select sql query
  • When softDeletes() is use with the parent, what is the best way to handle all of its child
  • error in uploading a sql file with data
  • Select count of records that have a relationship that has its own relationship condition?
  • using basic join for sql query for multiple values
  • Selecting multiple tables with matching columns but only displaying unique results
  • Use COUNT(), ORDER BY and WHERE user = ? simultaneously
  • adding a record to database through slick scala
  • Selecting many rows of binary data from MySQL, into dumpfiles
  • splitting up timeFrom and timeTo into hour intervals
  • SQL Injection on BadStore
  • SQL - Setting a maximum number when incrementing a value by 1
  • MySql - Join, Sum, and return the Sums as columns
  • How can I join a table on two fields and retrieve a single column from both matching results?
  • Ruby: Cleanup my code w/ stored procedure?
  • How to structure a MySQL database for counties, cities, and states
  • User-Defined Functions Returning Table in MySQL
  • How would I return the result of SQL math operations?
  • MySQL fetch parent and all children
  • Create a mysql database and use normalization
  • Ruby: Sequel gem Insert to Mysql
  • Tryton ERP MySQL installation
  • Show the most recently added row in a table for each distinct name
  • Rake task that purge just a single table
  • Amazon RDS MySQL support for JSON functions
  • cakephp join for selectbox
  • Column width of mysql output
  • SQL: Specifying a unique constraint through a foreign key and efficiently querying it
  • SQL add space in column string
  • Get Max value, Distinct values from Table in MySQL
  • MySQL select rows based on two tables
  • Dealing With The Type Blob within Scala's Case Classes
  • mysql limit and offset in large table
  • No MySQL driver selectable in JBoss new Datasource wizard
  • Drupal db_insert('node') promote to front page equel to 1 not working
  • How can we show records even if id is null?
  • How to retrieve the last 30 days records for a user from current date
  • How to stop a running procedure in MySQL?
  • How to merge the tailing fields in a sorted result in SQL?
  • Error (2014. Commands out of querys) with all complex querys on MySQL
  • Slow Query Execution joining multiple tables
  • Is there a way to add header to mysql query results?
  • creating CRUD inserting issue
  • sub queries error
  • SQL / MySQL: Sum all amounts for respective month
  • join 2 mysql select based on text field
  • Bluemix- Bind Mobilefirst Container to Cloud Foundry-App
  • joining two table and show the attribute name instead of id
  • How to correct the following query
  • Error while creating a table
  • How to export database through putty?
  • mysql : How to update or insert new rows DAILY?
  • Is there a way to retrieve the minimum value of a datatype in MySQL?
  • printing numbers 1 to 100 with 10 numbers per line
  • shadow
    Privacy Policy - Terms - Contact Us © animezone.co