From 79a77ac9322782182c14bbad1b25172103021b92 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Mikael=20Lepist=C3=B6?= Join Methods
Creates an update query, taking a hash of properties or a key/value pair
to be updated based on the other query constraints. Resolves the promise / fulfills the
- callback with the number of affected rows for the query.
+ callback with the number of affected rows for the query. If a key to be updated has value
+ undefined it is ignored.
knex('books') .where('published_date', '<', 2000) .update({ - status: 'archived' + status: 'archived', + thisKeyIsSkipped: undefined })diff --git a/src/query/compiler.js b/src/query/compiler.js index 9676c01522..07ddfc92c5 100644 --- a/src/query/compiler.js +++ b/src/query/compiler.js @@ -396,6 +396,7 @@ assign(QueryCompiler.prototype, { // "Preps" the update. _prepUpdate: function(data) { + data = _.omit(data, _.isUndefined) var vals = [] var sorted = Object.keys(data).sort() var i = -1 diff --git a/test/unit/query/builder.js b/test/unit/query/builder.js index 661d6dcda3..3896a9ced6 100644 --- a/test/unit/query/builder.js +++ b/test/unit/query/builder.js @@ -2129,6 +2129,19 @@ describe("QueryBuilder", function() { }); }); + it("should not update columns undefined values", function() { + testsql(qb().update({'email': 'foo', 'name': undefined}).table('users').where('id', '=', 1), { + mysql: { + sql: 'update `users` set `email` = ? where `id` = ?', + bindings: ['foo', 1] + }, + default: { + sql: 'update "users" set "email" = ? where "id" = ?', + bindings: ['foo', 1] + } + }); + }); + it("should allow for 'null' updates", function() { testsql(qb().update({email: null, 'name': 'bar'}).table('users').where('id', 1), { mysql: {