Says we have two Tables: customers and shops, we set customers.id as primary-key
and shops.company_id as foreign-key
what we need is a data-format like this: [{id: customerid, shop: shopamount}]
, take a look at my code:
Customers
// define a global-variable to store data preparing to return
var CUSTOMER_DATA = []
var Customers = db.define('customers', {
id: Sequelize.INTEGER
})
Shops
var Shops = db.define('shops', {}, {
classMethods: {
// count shop numbers based on company.id
countShop: function (id, callback) {
Shops
.count({
where: {
company_id: id
}
})
.complete(function (num) {
// return shop number
callback(num)
})
}
}
})
And logic goes here:
Customers
.findAll()
.complete(function (error, customers) {
customers.each(function (customer) {
var data = {}
data.id = customer.dataValues.id
// pass customer id to countShop method
Shops.countShop(data.id, function (num) {
data.shop = num
// here I get stuck, I have no idea how to detect when **each** is done
// and export CUSTOMER_DATA
CUSTOMER_DATA.push(data)
})
})
})
I wonder the way I accomplish this is the right way and how to export CUSTOMER_DATA, thanks in advance!