Fix MySQL conversion for embedded model instance

This commit is contained in:
Raymond Feng 2014-08-20 14:25:53 -07:00
parent 7344088cc6
commit ea51841f5e
1 changed files with 13 additions and 5 deletions

View File

@ -237,7 +237,7 @@ MySQL.prototype.updateOrCreate = MySQL.prototype.save = function (model, data, c
if (props[key] || mysql.id(model, key)) {
var k = mysql.columnEscaped(model, key);
var v;
v = mysql.toDatabase(props[key], data[key]);
v = mysql.toDatabase(props[key], data[key], true);
if (v !== undefined) {
fieldsNames.push(k);
fieldValues.push(v);
@ -267,7 +267,7 @@ MySQL.prototype.toFields = function (model, data) {
var props = this._models[model].properties;
Object.keys(data).forEach(function (key) {
if (props[key]) {
var value = this.toDatabase(props[key], data[key]);
var value = this.toDatabase(props[key], data[key], true);
if (undefined === value) {
return;
}
@ -296,11 +296,11 @@ function dateToMysql(val) {
* @param val
* @returns {*}
*/
MySQL.prototype.toDatabase = function (prop, val) {
MySQL.prototype.toDatabase = function (prop, val, forCreate) {
if (val === null || val === undefined) {
return 'NULL';
}
if (val.constructor.name === 'Object') {
if (!forCreate && val.constructor.name === 'Object') {
var operator = Object.keys(val)[0]
val = val[operator];
if (operator === 'between') {
@ -345,6 +345,10 @@ MySQL.prototype.toDatabase = function (prop, val) {
return this.client.escape(val);
}
if (typeof prop.type === 'function') {
if (prop.type.modelName) {
// For embedded models
return this.client.escape(JSON.stringify(val));
}
return this.client.escape(prop.type(val));
}
return this.client.escape(val.toString());
@ -365,7 +369,11 @@ MySQL.prototype.fromDatabase = function (model, data) {
for (var p in props) {
var key = this.column(model, p);
var val = data[key];
if (typeof val === 'undefined' || val === null) {
if (val === undefined) {
continue;
}
if (val === null) {
json[p] = null;
continue;
}
if (props[p]) {