不要怂,就是干,撸起袖子干!

Commit 10f60d4a by Sascha Depold

treat joins correctly

1 parent 67394b63
Showing with 30 additions and 3 deletions
...@@ -66,8 +66,9 @@ module.exports = (function() { ...@@ -66,8 +66,9 @@ module.exports = (function() {
} }
var onSuccess = function(results, fields) { var onSuccess = function(results, fields) {
var result = this.callee var result = this.callee
, self = this , self = this
, hasJoin = !!results[0] && (Utils._.keys(results[0]).length > 1) && (Utils.isHash(results[0][Utils._.keys(results[0])[0]]))
// add the inserted row id to the instance // add the inserted row id to the instance
if (this.callee && (this.sql.indexOf('INSERT INTO') === 0) && (results.hasOwnProperty('insertId'))) { if (this.callee && (this.sql.indexOf('INSERT INTO') === 0) && (results.hasOwnProperty('insertId'))) {
...@@ -77,8 +78,34 @@ module.exports = (function() { ...@@ -77,8 +78,34 @@ module.exports = (function() {
if (this.sql.indexOf('SELECT') === 0) { if (this.sql.indexOf('SELECT') === 0) {
// transform results into real model instances // transform results into real model instances
// return the first real model instance if options.plain is set (e.g. Model.find) // return the first real model instance if options.plain is set (e.g. Model.find)
if(this.options.raw) { if (this.options.raw) {
result = results result = results
} else if (hasJoin) {
result = results.map(function(result) {
var dao = this.callee.build(result[this.callee.tableName], { isNewRecord: false })
for (var tableName in result) {
if (result.hasOwnProperty(tableName) && (tableName !== this.callee.tableName)) {
var associatedDao = this.sequelize.daoFactoryManager.getDAO(tableName, { attribute: 'tableName' })
, association = this.callee.associations[tableName]
, accessor = Utils._.camelize(association.associationAccessor)
, daoInstance = associatedDao.build(result[tableName], { isNewRecord: false })
// downcase the first char
accessor = accessor.slice(0,1).toLowerCase() + accessor.slice(1)
if (['BelongsTo', 'HasOne'].indexOf(association.associationType) > -1) {
accessor = Utils.singularize(accessor)
dao[accessor] = daoInstance
} else {
dao[accessor] = dao[accessor] || []
dao[accessor].push(daoInstance)
}
}
}
return dao
}.bind(this))
} else { } else {
result = results.map(function(result) { result = results.map(function(result) {
return self.callee.build(result, { isNewRecord: false }) return self.callee.build(result, { isNewRecord: false })
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!