Created
April 22, 2016 22:05
-
-
Save helfer/eb46a1ff9ee46cea5fac247b5f469e7c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Sequelize from 'sequelize'; | |
import casual from 'casual'; | |
import _ from 'lodash'; | |
const db = new Sequelize('blog', null, null, { | |
dialect: 'sqlite', | |
storage: './blog.sqlite', | |
}); | |
const AuthorModel = db.define('author', { | |
firstName: { type: Sequelize.STRING }, | |
lastName: { type: Sequelize.STRING }, | |
}); | |
const PostModel = db.define('post', { | |
title: { type: Sequelize.STRING }, | |
text: { type: Sequelize.STRING }, | |
}); | |
AuthorModel.hasMany(PostModel); | |
PostModel.belongsTo(AuthorModel); | |
// create mock data with a seed, so we always get the same | |
casual.seed(123); | |
db.sync({ force: true }).then(() => { | |
_.times(10, () => { | |
return AuthorModel.create({ | |
firstName: casual.first_name, | |
lastName: casual.last_name, | |
}).then((author) => { | |
return author.createPost({ | |
title: `A post by ${author.firstName}`, | |
text: casual.sentences(3), | |
}); | |
}); | |
}); | |
}); | |
const Author = db.models.author; | |
const Post = db.models.post; | |
export { Author, Post }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
so createPost comes from the AuthorModel.hasMany(PostModel);. Here is the documentation: http://docs.sequelizejs.com/en/latest/api/associations/belongs-to/
Sequelize autocamelcases post from db.define('post'.... which createPost is a reference too. Be aware of plural and non-plural when using sequelize, because it does make a difference on how you data is added/removed from the database.