🎈 user.js
'use strict';
const { Model } = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class User extends Model {
static associate(models) {
models.User.hasMany(models.Buy,{ foreignKey: 'userId'})
}
}
User.init({
firstName: DataTypes.STRING,
lastName: DataTypes.STRING,
email: DataTypes.STRING,
hobby: DataTypes.STRING
}, {
sequelize,
modelName: 'User',
});
return User;
};
🎈 buy.js
'use strict';
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class buy extends Model {
static associate(models) {
buy.belongsTo(models.User, {
foreignKey: 'userId',
as : 'user',
onDelete:'NO ACTION'
});
}
}
buy.init({
userId: DataTypes.INTEGER,
buyName: DataTypes.STRING,
price: DataTypes.INTEGER
}, {
sequelize,
modelName: 'buy',
});
return buy;
};
🎈 create-user.js
'use strict';
/** @type {import('sequelize-cli').Migration} */
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.createTable('Users', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
firstName: {
type: Sequelize.STRING
},
lastName: {
type: Sequelize.STRING
},
email: {
type: Sequelize.STRING
},
hobby: {
type: Sequelize.STRING
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
async down(queryInterface, Sequelize) {
await queryInterface.dropTable('Users');
}
};
🎈 create-buy
'use strict';
/** @type {import('sequelize-cli').Migration} */
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.createTable('buys', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
userId: {
type: Sequelize.INTEGER
},
buyName: {
type: Sequelize.STRING
},
price: {
type: Sequelize.INTEGER
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
async down(queryInterface, Sequelize) {
await queryInterface.dropTable('buys');
}
};
🎈 user-buy-association < 외래키 설정 >
'use strict';
/** @type {import('sequelize-cli').Migration} */
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.addConstraint('buys', {
fields: [ 'userId' ],
type: 'foreign key',
name: 'buy_user_association',
references: {
table: 'Users',
field: 'id'
}
});
},
async down(queryInterface, Sequelize) {
await queryInterface.removeConstraint(
'buys',
'buy_user_association'
);
}
};
npx sequelize-cli migration:generate --name order-customer-manager-association
npx sequelize-cli migration:generate --name user-buy-association