express-example icon indicating copy to clipboard operation
express-example copied to clipboard

Add examples of associations

Open papb opened this issue 5 years ago • 1 comments

The new example does not show any associations; it would be very useful to show associations being performed as well as suggesting how to organize the code for that.

See https://github.com/sequelize/express-example/issues/95#issuecomment-660696270

papb avatar Jul 19 '20 19:07 papb

@papb Just trying to learn more about your code: May I ask why you used a modelDefiner function on each of these models? Why not just define the models in their file and import them like the following?

Your example:

const modelDefiners = [
	require('./models/user.model'),
	require('./models/instrument.model'),
	require('./models/orchestra.model'),
	// Add more models here...
	// require('./models/item'),
];

My example:

// top of file
const user = require('./models/user.model');
const instrument = require('./models/instrument.model');
const orchestra = require('./models/orchesta.model');

Inside of a model:

const instrument = sequelize.define('instrument', {
	// The following specification of the 'id' attribute could be omitted
	// since it is the default.
	id: {
		allowNull: false,
		autoIncrement: true,
		primaryKey: true,
		type: DataTypes.INTEGER
	},
	type: {
		allowNull: false,
		type: DataTypes.STRING,
	},
	// type: {
	// 	allowNull: false,
	// 	type: DataTypes.STRING,
	// 	validate: {
	// 		isIn: [['string', 'wind', 'percussion']]
	// 	}
	// },
	purchaseDate: {
		allowNull: false,
		type: DataTypes.DATE
	},
	// We also want it to have a 'orchestraId' field, but we don't have to define it here.
	// It will be defined automatically when Sequelize applies the associations.
	
	module.exports = instrument;
});

What's the advantage of the model files being functions that take sequelize as a parameter? Just trying to learn more!

NicholasEwing avatar Feb 20 '22 02:02 NicholasEwing