Last active
July 12, 2017 08:09
-
-
Save suhaotian/808ba38d24f9534eeef798287003b6f4 to your computer and use it in GitHub Desktop.
基于 Sequelize 的省市区表设计/导入/查询 实现 (mysql, sqlite, postgres)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = function(sequelize, DataTypes) { | |
var Area = sequelize.define("Area", { | |
name: DataTypes.STRING, | |
code: DataTypes.INTEGER, | |
type: DataTypes.STRING, | |
parent_code: DataTypes.INTEGER | |
}); | |
return Area; | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const models = require('./models') | |
const data = require('./china-address.js') | |
models.sequelize.sync().then(function() { | |
data.reduce((chain, province) => { | |
return chain.then(() => { | |
return models.Area.create({ | |
type: 'province', | |
name: province.name, | |
code: parseInt(province.code), | |
parent_code: 86, | |
}) | |
}).then(() => { | |
return province.city.reduce((chain2, city) => { | |
return chain2.then(() => { | |
return models.Area.create({ | |
type: 'city', | |
name: city.name, | |
code: parseInt(city.code), | |
parent_code: parseInt(province.code), | |
}) | |
}).then(() => { | |
return city.area.reduce((chain3, area) => { | |
return chain3.then(() => { | |
return models.Area.create({ | |
type: 'district', | |
name: area.name, | |
code: parseInt(area.code), | |
parent_code: parseInt(city.code), | |
}) | |
}) | |
}, Promise.resolve()) | |
}) | |
}, Promise.resolve()) | |
}) | |
}, Promise.resolve()).catch(e => { | |
console.log(e) | |
}) | |
}); | |
/* | |
reduceArrayPromise(data, (province) => { | |
return province.then(() => { | |
return reduceArrayPromise(province.city, (city) => { | |
return city.then(() => { | |
return reduceArrayPromise(city.area, () => {return 1}) | |
}) | |
}) | |
}) | |
}) | |
function reduceArrayPromise(arr, cb) { | |
return arr.reduce((chain, item) => { | |
return chain.then(() => { | |
return cb && cb(item) | |
}) | |
}, Promise.resolve()) | |
} | |
*/ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const models = require("./models"); | |
models.sequelize.sync().then(function() { | |
models.Area | |
.findAll({ | |
where: { | |
type: "city", | |
} | |
}) | |
.then(function(areas) { | |
console.log(areas.length) | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment