$ npm install
# after db setup
$ npx nodemon app.js
# now, point your browser to localhost:3000
First, initialize sequelize in your project using the CLI
$ npx sequelize-cli init
Then, update config/config.js
so you can use env vars, and update the .env
file with your env vars
// config/config.js
require('dotenv').config()
module.exports = {
development: {
username: process.env.DATABASE_USER,
password: process.env.DATABASE_PASSWORD,
database: process.env.DATABASE,
host: '127.0.0.1',
dialect: 'postgres'
}
}
Now, create your database
$ createdb catbook # set up your development database
# To generate a `Cat` model with attributes `name`, `breed`, `owner`
$ npx sequelize-cli model:generate --name Cat --attributes name:string,breed:string,owner:string
# To run migrations
$ npx sequelize-cli db:migrate
Cat
hasMany
Comments, CommentbelongsTo
Cat
To create the table associations using sequelize,
- Use sequelize-cli to generate a model for Comment, with attributes
text:string,CatId:integer
- Edit the generated migration file to specify that
CatId
is a foreign key by adding a reference to theCats
table primary key (id
)
CatId: {
type: Sequelize.INTEGER,
references: {
model: {
tableName: 'Cats'
},
key: 'id'
},
allowNull: false
}
- Run the migration
- Set properties on the model with values of the invoked association methods so that sequelize associates the models
// models/cat.js
class Cat extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
this.Comments = this.hasMany(models.Comment, { onDelete: 'cascade' })
}
}
// models/comment.js
class Comment extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
this.Cat = this.belongsTo(models.Cat)
}
}
- Use sequelize-cli to generate a model
Owner
with a name attribute and the corresponding migration file. - Associate the models and tables in 1:many relationships.
An owner has many cats and has many comments
A cat belongs to an owner (this might not be representative given cats think owners belong to them, but this is just an exercise..)
A comment belongs to an owner