Skip to content

Instantly share code, notes, and snippets.

@piouc
Created July 23, 2019 23:58
Show Gist options
  • Save piouc/43295b3d02d95ed81a6510a24ed1f223 to your computer and use it in GitHub Desktop.
Save piouc/43295b3d02d95ed81a6510a24ed1f223 to your computer and use it in GitHub Desktop.
sequelize
const Sequelize = require('sequelize')
const sequelize = new Sequelize({
dialect: 'sqlite',
storage: 'db.sqlite',
logging: (...args) => console.log(...args)
})
const Model = Sequelize.Model
class User extends Model {}
User.init({
name: {
type: Sequelize.STRING,
allowNull: false
}
}, {
underscored: true,
sequelize,
modelName: 'user'
})
class Tweet extends Model {}
Tweet.init({
message: {
type: Sequelize.STRING,
allowNull: false
}
}, {
underscored: true,
sequelize,
modelName: 'tweet'
})
User.hasMany(Tweet)
Tweet.belongsTo(User)
User.belongsToMany(User, {as: 'Follow', through: 'follow_follower'})
;(async () => {
await sequelize.sync()
const user1 = await User.create({
name: '1st'
})
const user2 = await User.create({
name: '2nd'
})
await user1.addFollow(user2)
const tweet = await Tweet.create({
message: 'hello world',
userId: user1.id
})
console.log(await User.findAll({
include: [
{
model: Tweet
}
]
}))
})()
{
"name": "sequelize-trial",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"sequelize": "^5.10.2",
"sqlite3": "^4.0.9"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment