javascript - Knex.JS Auto Update Trigger -
i using knex.js migration tools. however, when creating table, i'd have column named updated_at automatically updated when record updated in database.
for example, here table:
knex.schema.createtable('table_name', function(table) { table.increments(); table.string('name'); table.timestamp("created_at").defaultto(knex.fn.now()); table.timestamp("updated_at").defaultto(knex.fn.now()); table.timestamp("deleted_at"); }) the created_at , updated_at column defaults time record created, fine. but, when record updated, i'd updated_at column show new time updated @ automatically.
i'd prefer not write in raw postgres.
thanks!
you can create knex migration using timestamps:
exports.up = (knex, promise) => { return promise.all([ knex.schema.createtable('table_name', (table) => { table.increments(); table.string('name'); table.timestamps(false, true); table.timestamp('deleted_at').defaultto(knex.fn.now()); }) ]); }; exports.down = (knex, promise) => { return promise.all([ knex.schema.droptableifexists('table_name') ]); }; with timestamps database schema created adds created_at , updated_at column, each containing initial timestamp.
to keep updated_at column current, you'll need knex.raw:
table.timestamp('updated_at').defaultto(knex.raw('current_timestamp on update current_timestamp')); to skip knex.raw solution, suggest using high level orm objection.js. objection.js implement own basemodel updates updated_at column:
something.js
const basemodel = require('./basemodel'); class extends basemodel { constructor() { super(); } static tablename() { return 'table_name'; } } module.exports = something; basemodel
const knexfile = require('../../knexfile'); const knex = require('knex')(knexfile.development); const model = require('objection').model; class basemodel extends model { $beforeupdate() { this.updated_at = knex.fn.now(); } } module.exports = basemodel;
Comments
Post a Comment