ID photo of Ciro Santilli taken in 2013 right eyeCiro Santilli OurBigBook logoOurBigBook.com  Sponsor 中国独裁统治 China Dictatorship 新疆改造中心、六四事件、法轮功、郝海东、709大抓捕、2015巴拿马文件 邓家贵、低端人口、西藏骚乱
nodejs/sequelize/one_to_many_custom_column_name.js
#!/usr/bin/env node

// https://cirosantilli.com/sequelize-example

const assert = require('assert');
const path = require('path');
const { DataTypes, Op } = require('sequelize');
const common = require('./common')
const sequelize = common.sequelize(__filename, process.argv[2], { define: { timestamps: false } })
;(async () => {
const Country = sequelize.define('Country', {
  country_name: { type: DataTypes.STRING, unique: true },
});
const City = sequelize.define('City', {
  parent_country: { type: DataTypes.STRING },
  city_name: { type: DataTypes.STRING },
});
Country.hasMany(City, { foreignKey: 'parent_country', sourceKey: 'country_name' })
City.belongsTo(Country, { foreignKey: 'parent_country', targetKey: 'country_name' })
async function reset() {
  await sequelize.sync({force: true});
  await Country.create({country_name: 'germany'})
  await Country.create({country_name: 'france'})
  await City.create({parent_country: 'germany', city_name: 'berlin'});
  await City.create({parent_country: 'germany', city_name: 'munich'});
  await City.create({parent_country: 'france', city_name: 'paris'});
}
await reset()

{
  const rows = await City.findAll({
    where: { parent_country: 'germany' },
    include: {
			model: Country,
    }
  });
	assert.strictEqual(rows[0].Country.country_name, 'germany')
	assert.strictEqual(rows[1].Country.country_name, 'germany')
	assert.strictEqual(rows.length, 2)
}
})().finally(() => { return sequelize.close() });